如何在Tkinter中处理窗口关闭事件?
我该如何在Python Tkinter程序中处理窗口关闭事件(用户点击“X”按钮)呢?
相关问题:
11 个回答
19
如果你想改变关闭按钮(x按钮)的功能,或者让它不能关闭窗口,可以试试这个方法。
yourwindow.protocol("WM_DELETE_WINDOW", whatever)
然后你需要定义一下“whatever”是什么意思。
def whatever():
# Replace this with your own event for example:
print("oi don't press that button")
你还可以设置,当你关闭这个窗口时,可以像这样把它叫回来。
yourwindow.withdraw()
这个操作是隐藏窗口,但并不会真正关闭它。
yourwindow.deiconify()
这个操作会让窗口再次显示出来。
45
Matt展示了一种经典的关闭按钮修改方式。
另一种方式是让关闭按钮最小化窗口。
你可以通过使用iconify方法来实现这种效果,
将其作为protocol方法的第二个参数。
下面是一个在Windows 7和10上测试过的示例:
# Python 3
import tkinter
import tkinter.scrolledtext as scrolledtext
root = tkinter.Tk()
# make the top right close button minimize (iconify) the main window
root.protocol("WM_DELETE_WINDOW", root.iconify)
# make Esc exit the program
root.bind('<Escape>', lambda e: root.destroy())
# create a menu bar with an Exit command
menubar = tkinter.Menu(root)
filemenu = tkinter.Menu(menubar, tearoff=0)
filemenu.add_command(label="Exit", command=root.destroy)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
# create a Text widget with a Scrollbar attached
txt = scrolledtext.ScrolledText(root, undo=True)
txt['font'] = ('consolas', '12')
txt.pack(expand=True, fill='both')
root.mainloop()
在这个示例中,我们给用户提供了两种新的退出选项:
经典的文件菜单中的“退出”,以及Esc键。
299
Tkinter支持一种叫做协议处理器的机制。在这里,协议指的是应用程序和窗口管理器之间的互动。最常用的协议叫做WM_DELETE_WINDOW
,它用来定义当用户通过窗口管理器关闭窗口时会发生什么。
你可以使用protocol
方法来安装一个处理器,这个处理器是针对这个协议的(这个控件必须是Tk
或Toplevel
控件):
下面是一个具体的例子:
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
def on_closing():
if messagebox.askokcancel("Quit", "Do you want to quit?"):
root.destroy()
root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()