[Tutor] Tkinter threads

Dennis Lee Bieber wlfraed at ix.netcom.com
Mon Mar 7 19:30:17 EST 2022


On Tue, 8 Mar 2022 10:58:33 +1100, Phil <phillor9 at gmail.com> declaimed the
following:

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

	Not really.

	Pretty much all of the GUI frameworks operate where there is an "app"
object and, after doing all configuration of the GUI, does something like
"app.mainloop" or "app.run".

	The mainloop essentially consists of catching user interface events and
invoking callback methods to handle them. If any callbacks take a long time
to process, then the GUI "stutters" (sluggish) until the long running
callback returns to the mainloop.

	One CAN start threads to do long running computations, but those
threads must not manipulate the GUI itself. If the GUI needs to know when
such a thread has completed, the thread has to send a signal to the event
processing mainloop, which will trigger a signal specific callback that can
then update the GUI display state.

	The /other/ side is an "idle" handler, which gets called whenever the
GUI has no other events to process. Idle handlers can not be long running
tasks -- but if a long running task can be "paused" with saved state it can
do something like

if last_step = 0:
	do some stuff
elif last_step = 1:
	do another bit of task
elif last_step = 2:
	etc.
....

last_step = (last_step + 1) % number_of_steps
return

	last_step and any data that has to keep state between each invocation
may need to be global, or provided in some structure. So, making this a
method in a class would encapsulate the state.

class idle_process:
	def __init__(self):
		set up initial state
	def idle_worker(self):
		if self.last_step:
			....

and then, after instantiating it, provide

	instance.idle_worker

to the framework idle task system.


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/



More information about the Tutor mailing list