Binding or protocol for tkinter exit on Mac

Question:

My tkinter application, which usually runs on a Mac, needs to save some settings as it exits. If the application is exited by clicking the close box of the window, the following works great:

root.protocol("WM_DELETE_WINDOW", saveAndQuit)

however, it is more natural to exit on a Mac by typing Command-Q, and this protocol binding is not capturing that.

Is there an efficient way to bind "this application is about to exit" regardless of the exact manner of the exiting?

Asked By: Joymaker

||

Answers:

Is there an efficient way to bind "this application is about to exit"
regardless of the exact manner of the exiting?

Yes, root.bind('<Destroy>', save_and_quit). But you need to have the event parameter in your defined function.

def save_and_quit(event):
    #cleanup
Answered By: Thingamabobs

Thank you, JRiggles, for a successful pointer. Here was the minimal code that worked:

menubar = tk.Menu(root)
mac_app_menu = tk.Menu(menubar , name = "apple")
menubar.add_cascade(menu = mac_app_menu) 
root.createcommand("tk::mac::Quit" , save_and_quit)

I tend to think it’s an omission on the part of tkinter that root.bind('<Destroy>', ...)
does not catch absolutely every method of exiting the program.

Incidentally, the whole thing is kind of hokey because it does not actually change what is on the menu bar as it would appear to do, it just changes what this particular command does.

Answered By: Joymaker
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.