[Tutor] Countdown Clock Programming Question

Alan Gauld alan.gauld at btinternet.com
Tue Dec 15 12:10:43 EST 2015


On 15/12/15 14:18, Evan Sommer wrote:
> Hey there Alan!
> 
> So I tried some of your modifications, and they seem to be doing some
> pretty interesting things with the program. For some reason, now the
> program runs extremely fast, and doesn't now count down in one second
> intervals. I think this is a result of the root.after command. 

Yes, you are using it wrongly.
The root.after() function removes the need for your for loops.
You just call root after until the time reaches the point you are
interested in.

> def count_down(start, end):
>         root.after (1000, count_down)

You should be updating your display inside the count_down function.
This function, if done right, will get called each second. So every
second it will update your display until it reaches the end. So start
will be the value to display. stop will be the end value. When start==
stop the function will terminate.

It should look something like this:

def count_down(start,end):
    update display to show start
    if start > end:
       root.after(1000, lambda : count_down(start-1, end))


That pattern will simply count from start to end. If you want to change
colours etc then you need some more worjk.
But for now just try to get the counter working.


> for t in range(240, 120, -15):
>         # 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
>         root.after (1, count_down)

Replace the whole loop with a call to

root.after(1, lambda : count_down(240,0))

And put the display code into the count_down method.

Here is a very simple program that just counts down the seconds.
You can build on that to do all the other display tweaks you
want.

############################
import tkinter as tk

def count_down(start,stop):
   display['text'] = str(start)
   if start > stop:
        top.after(1000, lambda : count_down(start-1,stop))

top = tk.Tk()
display = tk.Button(top,text="Press",
                    command = lambda: count_down(10,0))
display.pack()
top.mainloop()
############################

Notice that there are no for loops involved.

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