tags:

views:

398

answers:

2

Ok, I would like to put together a Python/Tkinter dialog box that displays a simple message and self-destructs after N seconds. Is there a simple way to do this?

Thanks,

--Steve

+4  A: 

You can use the after function to call a fucntion after a delay elapsed and the destroy to close the window.

Here is an example

from Tkinter import *
root = Tk()
prompt = 'hello'
label1 = Label(root, text=prompt, width=len(prompt))
label1.pack()

def close_after_2s():
    root.destroy()

root.after(2000, close_after_2s)
root.mainloop()

Update: The after docstring says:

Call function once after given time.
MS specifies the time in milliseconds. 
FUNC gives the function which shall be called. 
Additional parameters are given as parameters to the function call.
Return identifier to cancel scheduling with after_cancel.
luc
Thanks--very helpful! Can you point me to reference documentation for the after() function?
Stephen Gross
Also, the next step is to update the contents of the label. Is there some trick to this? I tried 'label1.set('new text');label1.pack()' to no avail...
Stephen Gross
@Stephen Gross - I found docs here: http://infohost.nmt.edu/tcc/help/pubs/tkinter/universal.html
Fred Larson
Is there some restriction on the number of times you can call root.after() ? I wrote 'root.after(1000, do_this); root.after(2000, do_that)' and it appears to only execute the latter function. Am I doing something wrong?
Stephen Gross
A: 

you could also use a thread.
this example uses a Timer to call destroy() after a specified amount of time.

import threading
import Tkinter


root = Tkinter.Tk()
Tkinter.Frame(root, width=250, height=100).pack()
Tkinter.Label(root, text='Hello').place(x=10, y=10)

threading.Timer(3.0, root.destroy).start()

root.mainloop()
Corey Goldberg