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?

Matt Fenwick
  • 46,727
  • 21
  • 123
  • 189
apalopohapa
  • 4,513
  • 5
  • 25
  • 29

2 Answers2

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)
Bryan Oakley
  • 341,422
  • 46
  • 489
  • 636
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.

O.C.
  • 71
  • 1
  • 2