如何關閉一個 Tkinter 視窗?


使用 Tkinter 建立應用程式很容易,但有時,很難關閉視窗或框架,而不用在標題欄上透過按鈕關閉。在這種情況下,我們可以使用 .destroy() 方法關閉視窗。

由於 Tkinter 屬性是獨立的,因此我們可以建立一個單獨的方法,使用按鈕關閉視窗。

示例

#Import the library
from tkinter import *

#Create an instance of window
win = Tk()

#Set the geometry of the window
win.geometry("700x400")

#Define a function to close the window
def close_win():
   win.destroy()

#Create a label
Label(win, text="Click the button to Close the window",
font=('Poppins bold', 25)).pack(pady= 20)

#Create a Button

Button(win, text= "Close", font=('Poppins bold', 16),
command=close_win).pack(pady=20)

win.mainloop()

輸出

如果我們執行上面的程式碼,它將產生以下輸出視窗 −

更新於:2021-03-04

12000+ 瀏覽量

開啟你的 職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.