python - 在 tkinter 中关闭窗口之前执行某个命令
问题描述
我正在将 tkinter 与 python 一起使用。
按下关闭按钮时,是否可以在关闭窗口之前执行某个命令(例如 print ("hello"))?
我正在使用桌面环境的关闭按钮(以及最大化和最小化),而不是任何特殊的关闭按钮。
请注意,我问的是如何在关闭之前执行某个命令,而不是如何关闭窗口(这已经可以使用窗口按钮完成)。所以这不是这个问题的重复
解决方案
根据您在窗口关闭时要执行的操作,一种可能的解决方案是将您的 GUI 包装到一个类中,在with
语句中对其进行初始化,然后在__exit__()
方法中执行您的工作:
import tkinter
class MainWindow(object):
def __init__(self):
print("initiated ..")
self.root = tkinter.Tk()
def __enter__(self):
print("entered ..")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Main Window is closing, call any function you'd like here!")
with MainWindow() as w:
w.root.mainloop()
print("end of script ..")
推荐阅读
- java - 在 Java 中使用没有 Selenium 的 Browsermob 代理生成 Har-File 文件
- sql - 在查询中查询
- c++ - 为什么将静态添加到翻译单元中的所有函数可能会增加生成的目标文件的大小?
- html - 如何将内部 div 的 wdith 指定为百分比?
- php - 不能在视图中的 for 循环上使用 hasMany 关系(Laravel)
- mongodb - 从 MySQL 到 Mongoose:聚合文档,所有行中两个值的最大乘积
- c++ - 如何使用getline并提取字符串c ++的某些部分
- python - TypeError:无法在 Django 视图函数中解压不可迭代的 int 对象
- python - Python API:JSONDecodeError:预期值:第 1 行第 1 列
- angularjs - Angular - 尝试导入 Angular 模板显示 404 错误