Run an infinite loop in the backgroung in Tkinter

后端 未结 2 2014
慢半拍i
慢半拍i 2020-12-06 14:56

I would like the code to run in the background and to update my GUI periodically. How can I accomplish this?

For example, suppose I want to execute something like t

2条回答
  •  天命终不由人
    2020-12-06 15:38

    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.

    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) 
    

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

提交回复
热议问题