[Tutor] Tkinter threads

Peter Otten __peter__ at web.de
Tue Mar 8 03:36:15 EST 2022


On 08/03/2022 00:58, Phil wrote:
> Alan mentioned the use of threads when replying to the Class access
> rules thread.
>
>   # ideally put this loop in a thread
>
>  From what I understand, and I haven't researched this topic deeply,
> tkinter is not multithreaded. How might I put a loop into it's own thread?
>
> I have a project (Conway's game of life) where either the GUI or the
> calculation code needs to be in independent threads. The GUI is very
> sluggish to unresponsive while cell generations are being calculated.
> This is a wxpython project, perhaps tkinter handles threads in a way
> that's more understandable to the amateur programmer.
>


If you have a loop like

while some_condition:
     do_stuff()
     sleep(delay_in_seconds)

you don't have to put it into a separate thread.
Replace sleep() with Tk.after() instead:

class App(tk.Tk):
     def repeat_stuff(self):
         do_stuff()
         if not some_condition:
             self.after(delay_in_milliseconds, self.repeat_stuff)

root = App()
root.repeat_stuff()
root.mainloop()

This is under the assumption that do_stuff() doesn't take long enough to
produce an annoying lag in the GUI.

On the rare occasions where I've used tkinter with threads I've followed
a recipe by the late Fredrik Lundh:

https://web.archive.org/web/20170505053848/http://effbot.org/zone/tkinter-threads.htm

The threads write to a queue.Queue() that is polled by the main
(tkinter) thread.


These days there's also asyncio. I've yet to wrap my head around that,
though, so no sample code here :(


More information about the Tutor mailing list