在 Tkinter(Python)中,root.destroy() 和 root.quit() 有什麼區別?


當我們對 tkinter 視窗物件呼叫 destroy() 方法時,它將終止 mainloop 程序並銷燬視窗中的所有小部件。Tkinter destroy() 方法主要用於終止銷燬在後臺執行的直譯器。

然而,可以使用 quit() 方法來停止 mainloop() 函式之後的程序。我們可以透過建立一個按鈕物件來演示這兩種方法的功能。

示例

#Import the required libraries
from tkinter import *

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

#Set the geometry of frame
win.geometry("650x450")

#Define a function for Button Object
def quit_win():
   win.quit()
def destroy_win():
   win.destroy()

#Button for Quit Method
Button(win,text="Quit", command=quit_win, font=('Helvetica
bold',20)).pack(pady=5)

#Button for Destroy Method
Button(win, text= "Destroy", command=destroy_win, font=('Helvetica
bold',20)).pack(pady=5)
win.mainloop()

輸出

執行程式碼將顯示一個視窗,其中分別有兩個按鈕“退出”和“銷燬”。

警告 - quit() 會突然終止應用程式,因此建議你在執行後從管理器中關閉應用程式。

更新於: 26-Mar-2021

5K+ 瀏覽

開啟你的 職業生涯

完成課程,獲得認證

加入我們
廣告