首页 > 解决方案 > 在 Python 中使用 Tkinter 退出时的消息框对话框

问题描述

我想在按下“X”按钮关闭 GUI 时显示一个消息框对话框。我想问用户他是否确定他想用是/否选择退出程序。在对话框中按“是”时出现错误,如果按“否”则 GUI 关闭。 这是完整的代码

这是我得到的错误:

self.tk.call('destroy', self._w)

_tkinter.TclError:无法调用“destroy”命令:应用程序已被销毁

这是我到目前为止所做的:

import atexit

def deleteme():
     result = messagebox.askquestion("Exit", "Are You Sure You Want to Exit?")
     if result == "yes":
        root.destroy()
     else:
        return None

atexit.register(deleteme)

标签: pythonuser-interfacetkintermessagebox

解决方案


您可以使用该protocol方法将窗口删除与函数绑定。

from tkinter import *
from tkinter import messagebox

def on_close():
    response=messagebox.askyesno('Exit','Are you sure you want to exit?')
    if response:
        root.destroy()

root=Tk()
root.protocol('WM_DELETE_WINDOW',on_close)

root.mainloop()

更新

根据atexit模块的文档

这样注册的函数会在解释器正常终止时自动执行。

The function registered was called after the mainloop was destroyed (since nothing proceeds, it marks the end of program). The GUI element that the function tries to destroy doesn't exist anymore, as also stated by the error.

This module is not meant for the use case you trying to achieve, it's usually used for "cleanup" functions that are supposed to perform a task after the program terminates.

The callback registered via the WM_DELETE_WINDOW protocol gives you the control over what happens when the window is instructed to close.


推荐阅读