Run endless loop in backgroung in tkinter

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

For example, suppose I want to do something similar against the background of the GUI code that you 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() 
+3
source share
2 answers

It's a bit unclear what your code should do at the top, if you just want to call a function every second (or any number of seconds you want), you can use after .

So, if you just want to do something with textOne , you will 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 can make this function a method of your class (in this case I called it callback ), and your code will 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() 
+6
source

If you really want to start a separate infinite loop, you have no choice but to use a separate thread and exchange data through a thread safe queue. However, with the exception of rather unusual circumstances, you will never have to run an infinite loop. So, you already have an infinite loop: an event loop. So, when you say you want an infinite loop, you really ask how to make an infinite loop inside an infinite loop.

@mgilson gave a good example of how to do this using after , which you should try to try before trying to use streams. Threading does what you want, but it also makes your code significantly more complex.

+2
source

All Articles