【问题标题】:showing CPU usage in my program在我的程序中显示 CPU 使用率
【发布时间】:2017-07-13 08:16:24
【问题描述】:

尝试在我的 GUI 中显示 cpu 使用情况时出现此错误

cputext = tk.Label(self, text="CPU", cpu) ^ SyntaxError: 位置参数跟随关键字参数

这是我的代码

x = (2)
        while x > 0:
            cpu = psutil.cpu_percent(interval=1, percpu=False)
            cputext = tk.Label(self, text="CPU", cpu)
            cputext.pack()

当我这样打印时,没问题,但它正在控制台中打印

print("CPU Usage :", cpu)

【问题讨论】:

    标签: python-3.x tkinter label


    【解决方案1】:
    cputext = tk.Label(self, text="CPU", cpu)
    

    当您执行上述操作时,编译器会将cpu 视为Label 的一个选项,因为所有选项都用逗号分隔(就像selftext)。

    您需要预先格式化您的字符串或创建您的字符串并传递它。

    labelText = "CPU Usage : " +  str(cpu)
    tk.Label(self, text = labelText)
    

    cputext = tk.Label(self, text="CPU Usage : {}".format(cpu))
    

    【讨论】:

    • 感谢您的回答,现在没有错误但现在什么也没有发生,它不会打开GUI?
    • 这是因为你的 while 循环。如果您没有在任何地方更改 x 的值,则它是无限的,并且由于 tkinter 已经具有无限循环(mainloop),因此它不会显示任何内容。您应该寻找 .after 方法进行连续调用。
    • 再次感谢,知道了
    • 如果你能帮忙,我还有一个问题。所以上面的脚本我想计算 linux 服务器 CPU,但它计算我的 PC CPU,我已经连接到我的 linux 服务器 shell = sp.SshShell(hostname="ip", username="root", password="password" , missing_host_key=spur.ssh.MissingHostKey.accept)
    • @JackZara 抱歉,我不太了解这些。您可能想在搜索 google/SO 等后提出另一个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 2010-12-14
    相关资源
    最近更新 更多