Skip to content Skip to sidebar Skip to footer

Run An Infinite Loop In The Backgroung In Tkinter

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 this in the back

Solution 1:

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 = 0defincrement_textOne():
    textOne.x += 1# register "increment_textOne" to be called every 1 secself.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:

classFoo(Frame):

    def__init__(self, master=None):
        Frame.__init__(self, master)
        self.x = 0
        self.id = self.after(1000, self.callback)

    defcallback(self):
        self.x += 1print(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()

Solution 2:

If you truly want to run a distinct infinite loop you have no choice but to use a separate thread, and communicate via a thread safe queue. However, except under fairly unusual circumstances you should never need to run an infinite loop. Afte all, you already have an infinite loop running: the event loop. So, when you say you want an infinite loop you are really asking how to do an infinite loop inside an infinite loop.

@mgilson has given a good example on how to do that using after, which you should consider trying before trying to use threads. Threading makes what you want possible, but it also makes your code considerably more complex.

Post a Comment for "Run An Infinite Loop In The Backgroung In Tkinter"