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?
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?
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)
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.
The other answers are based on using the framework to detect when the application is ending, which is appropriate for things like "do you want to save"-dialogs.
For a cleanup-task I believe the pure python solution is more robust:
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(".")
Arguments are also allowed, see the official documentation for details https://docs.python.org/3/library/atexit.html#atexit.register
© 2022 - 2024 — McMap. All rights reserved.