[Tutor] Countdown Clock Programming Question
Alan Gauld
alan.gauld at btinternet.com
Tue Dec 1 12:33:47 EST 2015
On 01/12/15 10:16, Alan Gauld wrote:
>>> def count_down():
>>> # start with 4 minutes --> 240 seconds
>>> for t in range(240, 120, -1):
>>> # format as 2 digit integers, fills with zero to the left
>>> # divmod() gives minutes, seconds
>>> sf = "{:01d}:{:02d}".format(*divmod(t, 60))
>>> #print(sf) # test
>>> time_str.set(sf)
>>> root.update()
>>> # delay one second
>>> time.sleep(1)# create root/main window
>
> Don't use time.sleep() in a Tkinter program use the after
> method instead. In this case it will look like
>
> root.after(1000, count_down)
I just realized my advice is slightly contradictory.
If you add parameters to count_down you can't pass
it to after() directly. Instead you need to rewrite
count_down and use a little trick in after() like this:
def count_down(start, stop)
sf = "{:01d}:{:02d}".format(*divmod(start, 60))
time_str.set(sf)
root.update()
if start > stop:
root.after(1000, lambda: count_down(start-1,stop) )
Notice it has no loop, instead after() subtracts 1 second
from the start value each time it calls count_down.
--
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