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?
CodePudding user response:
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.
CodePudding user response:
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