在 Tkinter 中在一段時間後自動關閉視窗


為了關閉一個 Tkinter 應用程式,我們通常使用 destroy() 方法關閉父視窗。要在一個特定的時間限制之後自動關閉 Tkinter 視窗,我們必須使用 after(以毫秒錶示的時間,回撥) 方法,方法是指定時間和在一段時間限制後需要執行的回撥函式。

示例

#Import the required Libraries
from tkinter import *
from tkinter import ttk

#Create an instance of tkinter frame
win = Tk()

#Set the geometry of tkinter frame
win.geometry("750x270")

#Initialize a Label widget
Label(win, text= "This window will get closed after 3 seconds...",
font=('Helvetica 20 bold')).pack(pady=20)

#Automatically close the window after 3 seconds
win.after(3000,lambda:win.destroy())

win.mainloop()

輸出

執行以上程式碼將顯示一個視窗,該視窗將在 3 秒後關閉。

給定的輸出視窗將在 3 秒後關閉,可以透過更改 after (time, callback) 方法中的值來修改。

更新於: 30-Apr-2021

6K+ 瀏覽

開啟您的 職業

透過完成課程獲得認證

開始
廣告