Reputation: 67
So pretty much this is the code I have so far:
from tkinter import *
import time
root = Tk()
text = "Hello World"
theLabel = Label(root,text = text,font=("Arial",200),height = 100,)
theLabel.pack()
root.mainloop()
time.sleep(5)
How can I close the window after the program sleeps for 5 seconds? I have tried root.destroy()
but it didn't work.
Thanks in advance, Fargo
Upvotes: 1
Views: 562
Reputation: 1005
The code you have does not execute after root.mainloop()
.
Even if you do a simple print("Hello World")
statement after root.mainloop()
, it wont execute until your Tkinter window closes.
This is because root.mainloop()
is an infinte-loop, constantly running your tkinter window.
root.mainloop() #Runs your tkinter window
print("Hello World") #<-- Will not be executed until your root.mainloop() stops
So the question is: how do we get your "closing the window after 5 seconds" to work during root.mainloop
...
The answer is through the use of root.after(miliseconds,desiredFunction)
.
Here is your program with the desired effect of closing after 5 seconds:
from tkinter import *
import time
root = Tk()
text = "Hello World"
theLabel = Label(root,text = text,font=("Arial",200),height = 100,)
theLabel.pack()
#after 5000 miliseconds(5 seconds) of root being 'alive', execute root.destroy()
root.after(5000, root.destroy) #notice no parenthesis () after destroy
root.mainloop()
Hopefully this is what you were looking for!
Upvotes: 2