Tkinter 中關閉視窗的功能


無論何時我們執行一個 Tkinter 應用程式,它都會顯示一個基於 GUI 的視窗,其中包含小元件、框架和其他元素。假設我們希望使用一個函式來關閉我們的應用程式。Python Tkinter 中的 destroy() 方法用於在 mainloop 函式之後終止應用程式的正常執行。

示例

在此示例中,將建立一個button物件,觸發它以關閉應用程式。

#Import the tkinter library
from tkinter import *

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

#Set the geometry
win.geometry("650x250")

#Define a function
def close_app():
   win.destroy()

#Create a text Label
Label(win, text= "Click to close the Window", font= ('Helvetica bold', 14)).pack(pady=20)

#Create a Button for closing the window
button= Button(win, text= "Close", command= close_app, font=('Helvetica bold', 10))
button.pack(pady=10)
win.mainloop()

輸出

執行以上程式碼會顯示一個包含一個按鈕的視窗,該按鈕可用於關閉視窗。

現在,你可以單擊“關閉”按鈕以關閉視窗。

更新於:27-Mar-2021

1 千 + 瀏覽量

開啟你的職業生涯

完成課程,獲得認證

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