4

This code is an attempt to bind a command to a frame, ie. when the "Escape" key is pressed, the window should be destroyed.

from tkinter import *
from tkinter import ttk

root=Tk()
root.geometry("400x400")

frame1=ttk.Frame(root)
frame1.pack()

def Exit(event):
    root.destroy()

frame1.bind("<Escape>", Exit)

root.mainloop()

if frame1.bind() is replaced by root.bind(), the code works as I would expect it to. Why doesn't what I've written above work?

1 Answer 1

7

The bind works, but the event will only trigger if the frame has focus, and by default a frame does not have the keyboard focus.

Try setting the focus with frame1.focus_set()

Sign up to request clarification or add additional context in comments.

7 Comments

Ah, fantastic. So does changing the focus affect anything else? What sort of widgets normally have focus?
would wigits having the take_focus() method applied mess this up?
Changing the focus doesn't affect anything else. Widgets that take focus are any widgets that take input -- text widget, entry widget, etc. The take_focus() method doesn't "mess" things up per se, but it certainly can change the behavior as it is documented to do.
Yeah, I've just reread all the documentation with my new knowledge and the problem is solved. Thank you!
This is good, @Bryan. Maybe you also know why do key events (bindings) stop working after a tkMessageBox is displayed? (Mouse button events still work, though.) Re-focusing the frame (as you have suggested) doesn't help.
|

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.