更新 GTK、python 中的标签

use*_*445 4 python gtk

我现在正在学习GTK。感觉我在文档上浪费了时间。而且教程非常薄弱。

我正在尝试制作一个简单的应用程序,可以近乎实时地显示 CPU 的使用情况和温度,但我一直坚持更新标签。我知道 set_label("text") 但我不明白如何以及在哪里使用它。不用说,我是一个十足的菜鸟。

这是我的示例代码:

import subprocess
from gi.repository import Gtk
import sys
Run Code Online (Sandbox Code Playgroud)

获取CPU数据的类

class CpuData():

    # Get the CPU temperature
    @staticmethod
    def get_temp():
        # Get the output of "acpi -t"
        data = subprocess.check_output(["acpi", "-t"]).split()
        # Return the temperature
        temp = data[15].decode("utf-8")
        return temp


    # Get CPU usage percentage
    @staticmethod
    def get_usage():
        # Get the output of mpstat (% idle)
        data = subprocess.check_output(["mpstat"]).split()
        # Parses the output and calculates the % of use
        temp_usage = 100-float(data[-1])
        # Rounds usage to two decimal points
        rounded_usage = "{0:.2f}".format(temp_usage)
        return rounded_usage
Run Code Online (Sandbox Code Playgroud)

寡妇构造函数

class MyWindow(Gtk.ApplicationWindow):

    # Construct the window and the contents of the GTK Window
    def __init__(self, app):
        # Construct the window
        Gtk.Window.__init__(self, title="Welcome to GNOME", application=app)
        # Set the default size of the window
        self.set_default_size(200, 100)
Run Code Online (Sandbox Code Playgroud)

标签类

class MyLabel(Gtk.Label):
    def __init__(self):
        Gtk.Label.__init__(self)
        temp = CpuData.get_temp()
        # Set the label
        self.set_text(temp)
Run Code Online (Sandbox Code Playgroud)

应用程序构造函数

class MyApplication(Gtk.Application):

    def __init__(self):
        Gtk.Application.__init__(self)

    # Activate the window
    def do_activate(self):
        win = MyWindow(self)
        label = MyLabel()
        win.add(label)
        win.show_all()

    # Starts the application
    def do_startup(self):
        Gtk.Application.do_startup(self)

app = MyApplication()
exit_status = app.run(sys.argv)
sys.exit(exit_status)
Run Code Online (Sandbox Code Playgroud)

mam*_*e98 6

您应该通过超时调用所有方法:

GLib.timeout_add(ms, method, [arg])
Run Code Online (Sandbox Code Playgroud)

或者

GLib.timeout_add_seconds(s, method, [arg])
Run Code Online (Sandbox Code Playgroud)

其中ms是毫秒,s是秒(更新间隔),method将是 getUsage 和 getTemp 方法。您可以将标签传递为arg.

然后你只需要调用set_text(txt)标签上的方法

注意:您需要像这样导入 GLib:

from gi.repository import GLib
Run Code Online (Sandbox Code Playgroud)

编辑#1

正如 @jku 指出的,以下方法已经过时,可能只是为了提供与遗留代码的向后兼容性而存在(因此您不应该使用它们):


GObject.timeout_add(ms,method,  [arg])
Run Code Online (Sandbox Code Playgroud)

或者

GObject.timeout_add_seconds(s,method,  [arg])
Run Code Online (Sandbox Code Playgroud)

编辑#2

由于您的数据方法get_temp更加get_usage通用,您可以使用一些包装函数:

def updateLabels(labels):
    cpuLabel  = labels[0]
    tempLabel = labels[1]
    cpuLabel.set_text(CpuData.get_usage())
    tempLabel.set_text(CpuData.get_usage())
    return False
Run Code Online (Sandbox Code Playgroud)

然后简单地做:

GLib.timeout_add_seconds(1, updateLabels, [cpuLabel, tempLabel]) # Will update both labels once a second
Run Code Online (Sandbox Code Playgroud)

编辑#3

正如我所说,这是示例代码:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import GLib
import time


class TimeLabel(Gtk.Label):
    def __init__(self):
        Gtk.Label.__init__(self, "")
        GLib.timeout_add_seconds(1, self.updateTime)
        self.updateTime()


    def updateTime(self):
        timeStr = self.getTime()
        self.set_text(timeStr)
        return GLib.SOURCE_CONTINUE

    def getTime(self):
        return time.strftime("%c")


window = Gtk.Window()
window.set_border_width(15)
window.connect("destroy", Gtk.main_quit)

window.add(TimeLabel())
window.show_all()
Gtk.main()
Run Code Online (Sandbox Code Playgroud)