在Tkinter的背景中运行无限循环 [英] Run an infinite loop in the backgroung in Tkinter
问题描述
我希望代码在后台运行并定期更新我的GUI.我该怎么做?
I would like the code to run in the background and to update my GUI periodically. How can I accomplish this?
例如,假设我想在GUI代码的背景中执行类似的操作,如下所示:
For example, suppose I want to execute something like this in the background of the GUI code you can see below:
x = 0
while True:
print(x)
x = x + 1
time.sleep(1)
这是GUI代码:
class GUIFramework(Frame):
def __init__(self,master=None):
Frame.__init__(self,master)
self.master.title("Volume Monitor")
self.grid(padx=10, pady=10,sticky=N+S+E+W)
self.CreateWidgets()
def CreateWidgets(self):
textOne = Entry(self, width=2)
textOne.grid(row=1, column=0)
listbox = Listbox(self,relief=SUNKEN)
listbox.grid(row=5,rowspan=2,column=0,columnspan=4,sticky=N+W+S+E,pady=5)
listbox.insert(END,"This is an alert message.")
if __name__ == "__main__":
guiFrame = GUIFramework()
guiFrame.mainloop()
推荐答案
尚不清楚您顶部的代码应该做什么,但是,如果您只是想每秒调用一次函数(或每调用一次,每次调用一次)所需的秒数),则可以使用 after
方法.
It is a little unclear what your code at the top is supposed to do, however, if you just want to call a function every second (or every the amount of seconds you want), you can use the after
method.
因此,如果您只想对textOne
进行操作,则可能需要执行以下操作:
So, if you just want to do something with textOne
, you'd probably do something like:
...
textOne = Entry(self, width=2)
textOne.x = 0
def increment_textOne():
textOne.x += 1
# register "increment_textOne" to be called every 1 sec
self.after(1000, increment_textOne)
您可以将此函数作为您类的方法(在本例中,我将其称为callback
),您的代码将如下所示:
You could make this function a method of your class (in this case I called it callback
), and your code would look like this:
class Foo(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.x = 0
self.id = self.after(1000, self.callback)
def callback(self):
self.x += 1
print(self.x)
#You can cancel the call by doing "self.after_cancel(self.id)"
self.id = self.after(1000, self.callback)
gui = Foo()
gui.mainloop()
这篇关于在Tkinter的背景中运行无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!