【问题标题】:Run an infinite loop in the backgroung in Tkinter在 Tkinter 的后台运行无限循环
【发布时间】:2012-04-30 04:16:23
【问题描述】:

我希望代码在后台运行并定期更新我的 GUI。我怎样才能做到这一点?

例如,假设我想在你可以在下面看到的 GUI 代码的后台执行这样的事情:

x = 0

while True:
   print(x)
   x = x + 1
   time.sleep(1)

这是图形用户界面代码:

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()

【问题讨论】:

    标签: python loops tkinter


    【解决方案1】:

    有点不清楚您的顶部代码应该做什么,但是,如果您只想每秒(或您想要的每秒钟)调用一个函数,您可以使用after 方法.

    所以,如果你只想对textOne 做点什么,你可能会这样做:

    ...
    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),你的代码看起来像这样:

    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()
    

    【讨论】:

      【解决方案2】:

      如果您真的想运行一个独特的无限循环,您别无选择,只能使用单独的线程,并通过线程安全队列进行通信。但是,除非在相当不寻常的情况下,您永远不需要运行无限循环。毕竟,您已经运行了一个无限循环:事件循环。所以,当你说你想要一个无限循环时,你实际上是在问如何在无限循环中进行无限循环。

      @mgilson 给出了一个很好的例子,说明如何使用after 做到这一点,您应该在尝试使用线程之前先尝试一下。线程使您想要的成为可能,但它也使您的代码更加复杂。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-30
        • 2020-11-08
        • 1970-01-01
        • 1970-01-01
        • 2021-08-12
        • 2014-01-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多