[英]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.
当按下“Escape”键时,窗口应该被销毁。
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.如果
frame1.bind()
被替换为root.bind()
,代码会像我期望的那样工作。 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()
尝试使用
frame1.focus_set()
设置焦点
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.