在 Tkinter 的后台运行无限循环 [英] Run an infinite loop in the backgroung in Tkinter

查看:60
本文介绍了在 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)

这是图形用户界面代码:

This is the GUI code:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆