2016-04-14 129 views
1

关闭窗口,使相当多,这是我到目前为止的代码:Python 3 |在Tkinter的

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) 

我怎样才能程序后关闭窗口睡5秒?我试过root.destroy() 但它没有工作。

由于提前, 法戈

回答

1

你有没有root.mainloop()后执行代码。

即使您在root.mainloop()之后执行简单的print("Hello World")语句,它也不会执行,直到您的Tkinter窗口关闭。

这是因为root.mainloop()是infinte循环,不断地运行您的Tkinter窗口。

root.mainloop() #Runs your tkinter window 
    print("Hello World") #<-- Will not be executed until your root.mainloop() stops 

所以,问题是:我们如何让你的“5秒后关闭窗口”期间root.mainloop工作...

答案是通过使用root.after(miliseconds,desiredFunction)


这里是你的程序与关闭的预期效果5秒后:

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

希望这就是你要找的人! -Gunner

+0

_“不断运行你的tkinter窗口。”_并不完全如此。它不会“运行”一个窗口,它运行一个事件循环。也许这就是分裂毛发,但是你会让它听起来像是它一遍又一遍地运行你的程序,但事实并非如此。程序中的代码执行一次。 –