简体   繁体   中英

Why doesn't the .bind() method work with a frame widget in Tkinter?

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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM