[Tutor] Tkinter and threading

Alan Gauld alan.gauld at yahoo.co.uk
Thu Jun 2 12:24:33 EDT 2016


On 02/06/16 14:40, Marco Soldavini wrote:

> What if I want to run another loop beside the graphical interface in
> the same python script?

You need to do it in a separate thread.
Keep the Tkinter loop on your main thread and use it to trigger
actions.

> For example a state machine with a var state which can have some
> discrete string values (like RUNNING, STOPPED, PAUSED, ABORTED, IDLE)
> and a text element on the gui that reports that state.

A state machine should not need a loop! It should be triggered
by state changes alone. ie state should only be changed by
calling a function. That function sets the state value
and calls any processing function associated with the
transition. (Whether before or after you set value depends
on whether you are using Moore or Mealy semantics, in
practice it makes little difference.)

You might need a loop to detect (some of the) changes but
setting the state machine should be entirely separate.

> So a button cause a transition > the python loop (not the gui loop)
> detects the transition and changes the state var value > the gui
> refresh its value on screen.

The button generates an event.
The event causes an event-handling function to be called.
That function may well cause a state transition that your state
machine can detect. (But it could just as well call your state
machine directly)

> I wrote some code to try it without threading but it does not give the
> expected result as it seems the button update status action is already
> triggered. I am missing some basic point here

If you want two parallel event loops you pretty much need threads.
Without threads you need to develop some kind of event-driven callback
solution - which may very well be preferable!


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