[英]Python Threading
我正在嘗試制作一個簡單的程序,該程序可以不斷顯示和更新顯示CPU使用情況的標簽,同時進行其他不相關的事情。
我已經進行了足夠的研究,知道可能會涉及線程。 但是,我在將我在線程的簡單示例中看到的內容應用到我要執行的操作時遇到了麻煩。
我目前正在做什么:
import Tkinter
import psutil,time
from PIL import Image, ImageTk
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.labelVariable = Tkinter.StringVar()
self.label = Tkinter.Label(self,textvariable=self.labelVariable)
self.label.pack()
self.button = Tkinter.Button(self,text='button',command=self.A)
self.button.pack()
def A (self):
G = str(round(psutil.cpu_percent(), 1)) + '%'
print G
self.labelVariable.set(G)
def B (self):
print "hello"
if __name__ == "__main__":
app = simpleapp_tk(None)
app.mainloop()
在上面的代碼中,我基本上是在嘗試使命令A連續運行,同時允許用戶在按下按鈕時執行命令B。
您永遠不要嘗試從不是主線程的線程更改UI元素。
您可能想要的是after(delay_ms, callback, args)
。 一些信息可以在http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm上查看 。
作為示例,這是一個顯示時鍾的快速腳本( 注意:我從未真正使用過Tk)。
from Tkinter import *
from time import strftime
class App(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.label_var = StringVar()
self.label = Label(self, textvariable=self.label_var)
self.label.pack()
# Start the loop
self.go()
def go(self):
self.label_var.set(strftime("%H:%M:%S"))
# The callback is only called once, so call it every time
self.after(1000, self.go)
app = App()
mainloop()
您不需要線程即可完成如此簡單的任務。 您可以簡單地將任務安排為每秒運行一次,這可以通過“ after”方法完成。
首先,將此方法添加到您的simpleapp_tk類中:
def update(self):
G = str(round(psutil.cpu_percent(), 1)) + '%'
self.labelVariable.set(G)
self.after(1000, self.update)
然后,在您的initialize方法中添加以下調用:
self.update()
這將導致標簽更新為當前的cpu值。 然后,更新方法將自己重新計划以在一秒鍾內再次運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.