拦截 Tkinter“退出”命令?
我正在使用 Tkinter 用 Python 编写客户端-服务器程序。我需要服务器来跟踪连接的客户端。为此,我希望客户端在单击退出按钮(角落里的标准“X”)后向服务器发送一条自动消息。我如何知道用户何时退出程序?
I'm writing a client-server program in Python with Tkinter. I need the server to keep track of the connected clients. For this, I would like to have the client send an automated message to the server after the exit button(the standard "X" in the corner) is clicked. How can I know when the user is exiting the program?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您想要使用 wm_protocol 方法。具体来说,您对
WM_DELETE_WINDOW
协议感兴趣。如果您使用该方法,它允许您注册一个回调,该回调在窗口被销毁时调用。用法:
You want to use the wm_protocol method of the toplevel window. Specifically, you are interested in the
WM_DELETE_WINDOW
protocol. If you use that method, it allows you to register a callback which is called when the window is being destroyed.Usage:
您可以使用 python
atexit
模块。例如:
You can use python
atexit
module.For example:
就我而言,以下代码不起作用:
但是,它使用以下形式起作用:
In my case, the following code didn't work:
However, it worked using this form:
FWIW:也可以分配特定于小部件的行为。
如果您希望在销毁特定小部件时发生操作,您可以考虑重写 destroy() 方法。请参阅以下示例:
按下按钮“b2”时,框架“f”将被销毁,其中子框架“b1”和“Yo!”被打印。
我在 这个主题。
FWIW: It is also possible to assign a widget-specific behavior.
If you want an action to occur when a specific widget is destroyed, you may consider overriding the destroy() method. See the following example:
When the button 'b2' is pressed, the frame 'f' is destroyed, with the child 'b1' and "Yo!" is printed.
I posted the same answer on this topic.
不要忘记使用这样的 lambda:
Don't forget to use a lambda like this: