This code is an attempt to bind a command to a frame, ie. when the “Escape” key is pressed, the window should be destroyed.
JavaScript
x
16
16
1
from tkinter import *
2
from tkinter import ttk
3
4
root=Tk()
5
root.geometry("400x400")
6
7
frame1=ttk.Frame(root)
8
frame1.pack()
9
10
def Exit(event):
11
root.destroy()
12
13
frame1.bind("<Escape>", Exit)
14
15
root.mainloop()
16
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?
Advertisement
Answer
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()