class MainGUI(Tkinter.Tk):
# some overrides
# MAIN
gui = MainGUI(None)
gui.mainloop()
但是当用户关闭窗口时我需要进行一些清理。我可以重写 Tkinter.Tk 中的哪个方法?
如果您希望在销毁特定小部件时发生操作,您可以考虑覆盖 destroy() 方法。请参阅以下示例:
class MyButton(Tkinter.Button):
def destroy(self):
print "Yo!"
Tkinter.Button.destroy(self)
root = Tkinter.Tk()
f = Tkinter.Frame(root)
b1 = MyButton(f, text="Do nothing")
b1.pack()
f.pack()
b2 = Tkinter.Button(root, text="f.destroy", command=f.destroy)
b2.pack()
root.mainloop()
当按下按钮“b2”时,框架“f”被销毁,子框架“b1”和“哟!”已打印。
您可以设置一个在窗口被销毁时触发的绑定。绑定到
<Destroy>
或添加 WM_DELETE_WINDOW 协议处理程序。
例如:
def callback():
# your cleanup code here
...
root.protocol("WM_DELETE_WINDOW", callback)
其他答案基于使用框架来检测应用程序何时结束,这适用于“你想保存吗”对话框之类的事情。
对于清理任务,您还可以使用更强大的纯 python 解决方案:
import atexit
@atexit.register
def cleanup():
print("done")
# 'done' will be printed with or without one of these lines
# import sys; sys.exit(0)
# raise ValueError(".")
也允许带参数,具体参见官方文档 https://docs.python.org/3/library/atexit.html#atexit.register