Python Tkinter Canvas 无法绑定键盘 [英] Python Tkinter Canvas fail to bind keyboard

查看:43
本文介绍了Python Tkinter Canvas 无法绑定键盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在运行一个这样的小脚本

I've been running a small script like this

from Tkinter import *
root = Tk()
def callback(event):
    print "callback"
w = Canvas(root, width=300, height=300)
w.bind("<Key>", callback)
w.pack()
root.mainloop()

但是,在我的情况下没有处理键盘事件(我在窗口 7 上使用 python 2.7)

However, the keyboard event is not handled in my situation (I use python 2.7 on window 7)

如果我使用

w.bind("<Button-1>", callback)

一切正常.

所以,这真的让我感到困惑.请任何人告诉我为什么会发生这种情况,提前致谢.

So, this really puzzles me. Please anyone tell me why this's happening, thanks in advance.

推荐答案

键绑定仅在具有键盘焦点的小部件获得键事件时触发.默认情况下,画布获得键盘焦点.您可以使用 focus_set 方法为其设置焦点.通常,您会在鼠标按钮的绑定中执行此操作.

Key bindings only fire when the widget with the keyboard focus gets a key event. The canvas by default does not get keyboard focus. You can give it focus with the focus_set method. Typically you would do this in a binding on the mouse button.

将以下绑定添加到您的代码中,然后在画布中单击,您的键绑定将开始工作:

Add the following binding to your code, then click in the canvas and your key bindings will start to work:

w.bind("<1>", lambda event: w.focus_set())

这篇关于Python Tkinter Canvas 无法绑定键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆