3

I am building a GUI application using Python and Tkinter. I want to control the behavior of the program when the user closes it.

I've installed a new WM_DELETE_WINDOW protocol using:

root = Tk()
root.protocol("WM_DELETE_WINDOW", lambda: closes_gracefully())

This indeed is working when the user clicks the X button on the titlebar, but it is NOT working when the user presses ALT+F4.

I tried binding the key sequence: root.bind("<Alt-F4>", lambda: closes_gracefully()) but it did not work.

How can I capture the ALT+F4 event?

8
  • lambda: closes_gracefully() is just closes_gracefully, by the way. Commented Jan 24, 2017 at 8:28
  • 3
    Just tried in my app and this works well for me: self.bind('<Alt-Key-F4>', self.whatever_your_want) Commented Jan 24, 2017 at 8:29
  • Related: stackoverflow.com/questions/30157521/… Commented Jan 24, 2017 at 8:30
  • 2
    Your current code works fine for me. Please add a minimal reproducible example. Commented Jan 24, 2017 at 8:34
  • 1
    Just a note: Alt+F4 is platform dependent, for example Macs use Cmd+Q / Cmd+W. Commented Jan 24, 2017 at 9:41

1 Answer 1

3

For this purpose, you could use atexit.register.

It works like a stack that is executed when the program gets closed. Every time you do register(function), this function gets pushed on top. If you added a, b and c they get executed in the opposite order(c, b, a).

In your case, you should do:

register(closes_gracefully)

You should note that this works almost always, except with crashes(alt-f4 works too, just tested it).

You can even use register as a decorator when the function takes no parameters:

@register
def bye():
    print("I'm out!")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.