如何处理 Tkinter 中的窗口关闭事件? [英] How do I handle the window close event in Tkinter?

查看:61
本文介绍了如何处理 Tkinter 中的窗口关闭事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Python Tkinter 程序中处理窗口关闭事件(用户单击X"按钮)?

How do I handle the window close event (user clicking the 'X' button) in a Python Tkinter program?

推荐答案

Tkinter 支持一种名为 协议处理程序.这里,术语协议指的是应用程序和窗口管理器之间的交互.最常用的协议称为WM_DELETE_WINDOW,用于定义当用户使用窗口管理器显式关闭窗口时会发生什么.

Tkinter supports a mechanism called protocol handlers. Here, the term protocol refers to the interaction between the application and the window manager. The most commonly used protocol is called WM_DELETE_WINDOW, and is used to define what happens when the user explicitly closes a window using the window manager.

您可以使用 protocol 方法为该协议安装处理程序(小部件必须是 TkToplevel 小部件):

You can use the protocol method to install a handler for this protocol (the widget must be a Tk or Toplevel widget):

这里有一个具体的例子:

Here you have a concrete example:

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()

这篇关于如何处理 Tkinter 中的窗口关闭事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆