You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CustomTkinter GUI中标签不显示问题求助

问题原因及解决方案

问题出在get_cpu_usage()函数里的psutil.cpu_percent(interval=1):

  • interval=1会让函数阻塞主线程1秒来计算CPU使用率,而CustomTkinter的GUI运行在主线程中,阻塞会导致界面无法及时渲染、更新,所以你看不到任何文本显示。
  • 虽然控制台能正常输出,但GUI主线程被频繁阻塞,无法完成界面绘制。

修复步骤

  1. 移除psutil.cpu_percent()的interval参数,改为无参数调用,它会返回自上次调用以来的CPU使用率,不会阻塞主线程。
  2. 初始化时先调用一次get_cpu_usage()做预热,避免第一次显示0%的情况。

修改后的完整代码

import customtkinter as ctk
import psutil

ctk.set_appearance_mode("dark")
ctk.set_default_color_theme("green")

app = ctk.CTk()
app.geometry("320x240")

# 预热CPU使用率计算,避免第一次显示0%
psutil.cpu_percent()

# 获取CPU使用率
def get_cpu_usage():
    # 去掉interval参数,避免阻塞主线程
    return psutil.cpu_percent()

# 获取RAM使用率
def get_ram_usage():
    return psutil.virtual_memory().percent

# 创建显示系统状态的标签
cpu_label = ctk.CTkLabel(app, text="CPU Usage: ", fg_color="red")
cpu_label.pack(pady=10)
ram_label = ctk.CTkLabel(app, text="RAM Usage: ")
ram_label.pack(pady=10)

# 显示系统状态的主函数
def display_system_stats():
    cpu = get_cpu_usage()
    ram = get_ram_usage()
    
    # 控制台调试输出
    print(f'Updating stats: CPU Usage: {cpu}%, RAM Usage: {ram}%')
    
    cpu_label.configure(text=f'CPU Usage: {cpu}%')
    ram_label.configure(text=f'RAM Usage: {ram}%')
    
    app.after(2000, display_system_stats)

# 启动周期性更新
display_system_stats()

app.mainloop()

额外说明

  • 去掉app.after(0, display_system_stats),直接调用display_system_stats()即可启动更新,效果一致且更简洁。
  • 预热调用psutil.cpu_percent()是因为第一次无参数调用时,psutil会返回0%,后续调用才会返回正确的使用率,提前调用可以让第一次显示的数值就准确。

内容的提问来源于stack exchange,提问作者bpt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 08:52:07