Which method can I override for cleanup task when a Tkinter.Tk window in Python?
Asked Answered
P

3

1
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?

Prurigo answered 2/6, 2010 at 1:13 Comment(0)
O
5

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)
Offend answered 2/6, 2010 at 12:59 Comment(0)
T
5

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.

Trilemma answered 9/2, 2011 at 19:19 Comment(0)
F
0

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

Foreknowledge answered 30/8, 2023 at 6:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.