This question already has an answer here:
When the user presses a close Button
that I created, some tasks are performed before exiting. However, if the user clicks on the [X]
button in the top-right of the window to close the window, I cannot perform these tasks.
How can I override what happens when the user clicks [X]
button?
Using the method
procotol
, we can redefine theWM_DELETE_WINDOW
protocol by associating with it the call to a function, in this case the function is calledon_exit
:I found a reference on Tkinter here. It's not perfect, but covers nearly everything I ever needed. I figure section 30.3 (Event types) helps, it tells us that there's a "Destroy" event for widgets. I suppose .bind()ing your saving jobs to that event of your main window should do the trick.
You could also call mainwindow.overrideredirect(True) (section 24), which disables minimizing, resizing and closing via the buttons in the title bar.
The command you are looking for is
wm_protocol
, giving it"WM_DELETE_WINDOW"
as the protocol to bind to. It lets you define a procedure to call when the window manager closes the window (which is what happens when you click the[x]
).It sounds as if your save window should be modal.
If this is a basic save window, why are you reinventing the wheel?
Tk
has atkFileDialog
for this purpose.If what you want is to override the default behaviour of destroying the window, you can simply do:
This way, you can intercept the
destroy()
call when someone closes the window (by any means) and do what you like.