在GTK,Python中更新标签 [英] Update a label in GTK, python
问题描述
此刻我正在学习GTK.感觉就像我在浪费时间在文档上一样.而且教程很薄.
I am learning GTK at the moment. Feels like i am loosing my time with the documentation. And tutorials are pretty thin.
我正在尝试制作一个可以实时显示我的CPU使用情况和温度的简单应用程序,但是我一直坚持更新标签.我知道set_label("text"),但是我不知道如何以及在哪里使用它. 不用说,我是一个完整的菜鸟.
I am trying to make a simple app that can display my CPU's usage and temperature in near real time but i am stuck at updating the label. I am aware of set_label("text") but i don't understand how and where to use it. Needless to say, i am a complete noob.
这是我的示例代码:
import subprocess
from gi.repository import Gtk
import sys
获取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
寡妇构造函数
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)
标签类别
class MyLabel(Gtk.Label):
def __init__(self):
Gtk.Label.__init__(self)
temp = CpuData.get_temp()
# Set the label
self.set_text(temp)
应用程序构造函数
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)
推荐答案
您应该通过超时调用所有方法:
You should call all your methods via a timeout:
GLib.timeout_add(ms, method, [arg])
或
GLib.timeout_add_seconds(s, method, [arg])
其中,ms
是毫秒,而s
是秒(更新间隔),而method
是您的getUsage和getTemp方法.您可以将标签作为arg
传递.
where ms
are milliseconds and s
are seconds (update interval) and method
would be you getUsage and getTemp methods. You can pass the labels as arg
.
然后,您只需要在标签上调用set_text(txt)
方法
Then you just have to call the set_text(txt)
method on the label(s)
注意:您需要这样导入GLib:
Note: You need to import GLib like this:
from gi.repository import GLib
编辑#1
如@jku所指出的,以下方法已经过时,可能只是存在以提供与旧代码的向后兼容性(因此您不应使用它们):
EDIT #1
As @jku pointed out, the following methods are outdated and maybe just exist to provide backward compatability with legacy code (so you should not use them):
GObject.timeout_add(ms,method, [arg])
或
GObject.timeout_add_seconds(s,method, [arg])
编辑#2
由于数据方法get_temp
和get_usage
更通用,因此可以使用一些包装函数:
EDIT #2
As your data methods get_temp
and get_usage
are more universal, you can use a little wraper function:
def updateLabels(labels):
cpuLabel = labels[0]
tempLabel = labels[1]
cpuLabel.set_text(CpuData.get_usage())
tempLabel.set_text(CpuData.get_usage())
return False
然后简单地做:
GLib.timeout_add_seconds(1, updateLabels, [cpuLabel, tempLabel]) # Will update both labels once a second
编辑#3
正如我所说,这是示例代码:
EDIT #3
As I said, here is the example code:
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()
这篇关于在GTK,Python中更新标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!