[Tutor] cannot get a label message to display immediately
Alan Gauld
alan.gauld at btinternet.com
Fri Aug 14 22:06:18 CEST 2015
On 14/08/15 17:32, Bill Allen wrote:
> I am working in Tkinter. The scenario is that I click a button that
> starts a function running. No problem there. However, the function may
> take some time to run
That's the problem right there. You should never kick of an event
handler that takes a long time to run. Either:
1) Kick of a separate thread to do the back end processing
2) break the function into short chunks and use a timer
(after() in Tkinter) to repeatedly fire the function
(this is the traditional GUI approach)
3) In Python 3.4 use asyncore to create an asynchronous event
loop and feed the functions into that.
Any of these will stop the GUI hanging and enable intermediate
updates (eg a progress bar or countdown) to happen.
> How do I get both actions to happen essentially at the same time, the
> writing of the label and the execution of the function?
Using the simplest (but least efficient) timer approach convert
code like:
def long_handler():
for item in data:
processItem(item)
# wait..... for the loop to end
to
def long_handler()
update_status() # change the GUI
getItem(data) # fetch one item from data
processItem(item) # process one item,
if data: # is there any more?
after(20, long_handler) # then go again after 20ms
This then processes the data items at a rate of 50/second until they
complete. You can reduce the delay but there reaches a limit where
the returns reduce.
Using threads and/or asyncore should allow you to process the
data in one go in the background with control still returning
to the GUI. But its more complex to set up and test and asyncore
is very new and network focused (Py3.4 only) although in principle
is generic . At this point I'd recommend threads if you have
large data loads to process and asyncore if yuu have a lot of networking
to do.
HTH
--
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