问题
class MainGUI(Tkinter.Tk):
# some overrides
# MAIN
gui = MainGUI(None)
gui.mainloop()
But I need to do some cleanup when the window is closed by the user. Which method in Tkinter.Tk can I override?
回答1:
if you want an action to occur when a specific widget is destroyed, you may consider overriding the destroy() method. See the following example:
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()
When the button 'b2' is pressed, the frame 'f' is destroyed, with the child 'b1' and "Yo!" is printed.
回答2:
You can set up a binding that gets fired when the window is destroyed. Either bind to <Destroy>
or add a protocol handler for WM_DELETE_WINDOW.
For example:
def callback():
# your cleanup code here
...
root.protocol("WM_DELETE_WINDOW", callback)
来源:https://stackoverflow.com/questions/2954396/which-method-can-i-override-for-cleanup-task-when-a-tkinter-tk-window-in-python