Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...