如何使用按钮关闭 Tkinter 窗口
-
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()
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn