python - 在 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)
解决方案
您可以使用该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.
推荐阅读
- logstash - 即使管道失败,Docker 上的 Logstash 也会继续运行
- python - Strange behavior when dragging a QTreeWidgetItem on macOS Sierra
- java - Can not extract Double[] from resultset
- deep-learning - 文学中“权重捆绑”表达的形式意义
- ios - 启用断点后,Xcode 10 在运行后自动停止
- javascript - 如何将主页内容与反应路由器中的其余页面分开?
- azure - 服务器的内存缓存能否在 Azure 中使用?
- angular - 维护 UI (Angular 4) 和 JAVA 之间的会话
- python - 如何将代码片段添加到 python docstring(不是 doctest)?
- sql - 使用 sql 查询将值按列添加到特定行中