[Tutor] Tkinter threads

Alan Gauld alan.gauld at yahoo.co.uk
Mon Mar 7 20:48:30 EST 2022


On 07/03/2022 23: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?

By not putting it in the Tkinter part of your code.
If you also adopt the Model/View paradigm then the threading is
in the non Tkinter Model part of your code. It periodically
updates the state of the Led.

Meanwhile the Tkinter code is running in its own thread(usually the main
one!) and when needed it reads the current state of the Led (see the
other discussion about the View object) and displays it, quite oblivious
to the existence of any threads.

> 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. 

You could use the same approach but Python threading has a gotcha which
is that it doesn't really hep if the thread does not block for any I/O
or memory/file access. So you might need concurrency instead.

However, for a game of life program this shouldn't really be a problem
unless your cell colony is gigantic! And usually there is very little
interaction by users, the colony, once started, just runs to completion.
But in most games of life I've written it's more likely that I'd be
putting in sleep() statements to create a pause between displays rather
than needing to wait for the calculations. Are you sure you are
calculating efficiently?

> This is a wxpython project, perhaps tkinter handles threads

Very few GUIs "handle threads" because they usually run in the top
level thread and any threads are started by the model objects.
But threading is always a risky approach and only advised when
absolutely necessary. (Like your toggle loop which would, without
threading, lock up the program indefinitely! There are other
approaches you can use but threading is probably the simplest
in this simple case)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list