如何使用按鈕關閉 Tkinter 視窗
Jinku Hu
2023年1月30日
Tkinter
Tkinter Button
-
root.destroy()類方法關閉 Tkinter 視窗 -
destroy()非類方法關閉 Tkinter 視窗 -
直接將
root.destroy函式與按鈕的command屬性關聯 -
root.quit關閉 Tkinter 視窗
當使用者單擊 Tkinter 按鈕時,我們可以使用附加在按鈕上的函式或命令來關閉 Tkinter GUI。
root.destroy() 類方法關閉 Tkinter 視窗
try:
import Tkinter as tk
except:
import tkinter as tk
class Test:
def __init__(self):
self.root = tk.Tk()
self.root.geometry("100x50")
button = tk.Button(self.root, text="Click and Quit", command=self.quit)
button.pack()
self.root.mainloop()
def quit(self):
self.root.destroy()
app = Test()
destroy() 用來關閉視窗。

destroy() 非類方法關閉 Tkinter 視窗
try:
import Tkinter as tk
except:
import tkinter as tk
root = tk.Tk()
root.geometry("100x50")
def close_window():
root.destroy()
button = tk.Button(text="Click and Quit", command=close_window)
button.pack()
root.mainloop()
直接將 root.destroy 函式與按鈕的 command 屬性關聯
我們可以直接將 root.destroy 函式繫結到按鈕 command 屬性,而無需定義額外的 close_window 函式。
try:
import Tkinter as tk
except:
import tkinter as tk
root = tk.Tk()
root.geometry("100x50")
button = tk.Button(text="Click and Quit", command=root.destroy)
button.pack()
root.mainloop()
root.quit 關閉 Tkinter 視窗
root.quit 不僅退出 Tkinter 視窗,而且退出整個 Tcl 直譯器。
如果你的 Tkinter 應用不是從 Python Idle 啟動的,可以使用這種方法。如果從 Idle 呼叫你的 Tkinter 應用程式,則不建議使用 root.quit,因為 quit 不僅會殺死你的 Tkinter 應用程式,還會殺死 Idle 本身,因為 Idle 也是 Tkinter 應用程式。
try:
import Tkinter as tk
except:
import tkinter as tk
root = tk.Tk()
root.geometry("100x50")
button = tk.Button(text="Click and Quit", command=root.quit)
button.pack()
root.mainloop()
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Jinku Hu
