[Tutor] please help me with after method

Alan Gauld alan.gauld at yahoo.co.uk
Wed Nov 16 19:03:37 EST 2016


On 16/11/16 18:48, Freedom Peacemaker wrote:
> Hi, i need help. I am using Python 3.4 and I have wrote little app for
> windows only ( windows 7 and higher). Its timer and my app working but not
> good. Some people said that i should use after method instead of update()

after() executes a function after a delay.
In your case you could use it to trigger an
immediate shutdown after the delay elapses.
But I'm not sure that would be much better
than doing what you are doing.

The other use of after is to avoid loops in
event handlers such as the one you have here.
This allows control to return to the GUI window.

See below...

> When you run app first enter minutes in entry then press start. If you
> first press start your pc will shutdown with no time to stop it

You can fix that by setting a default value for the time.
But you still need to write some code to cancel the shutdown
(by killing the process perhaps?)

> def startCount():
>     setTime = setMinutes.get() * 60
>     strTime = str(setTime)
>     timeSet = ("\""+"shutdown /s /f /t " +strTime+"\"")
>     os.system(timeSet)

Up to here is fine but you don't want a long running loop
inside an event handler. Although, in this case, it probably
doesn't run for long, it just counts down very quickly.

Instead you want it to count down  every second or so.

So you want to call a function that displays the time
remaining then calls after() with a delay of 1 second.
The call to after should have the same function in it.
Like so:

def displayCountdown():
    # display the time here
    # decrement the time by 1 second
    # if any time remains:
    #    call after(1000,displayCountdown) # 1000ms = 1s

Note that after only needs the function name, don't
include any parentheses.

>     for t in range(setTime, -1, -1):
>         lcd = "{:02d}:{:02d}".format(*divmod(t, 60))
>         timeString.set(lcd)
>         try:
>             root.update()
>         except TclError:
>             messagebox.showinfo('Info', 'Closing app wont stop timer.')
>             return
>         time.sleep(1)
>     return


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