你有沒有不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
_「不斷運行你的tkinter窗口。」_並不完全如此。它不會「運行」一個窗口,它運行一個事件循環。也許這就是分裂毛髮,但是你會讓它聽起來像是它一遍又一遍地運行你的程序,但事實並非如此。程序中的代碼執行一次。 –