如何使用按钮关闭 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()
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。