首页 > 解决方案 > 如何添加键绑定?

问题描述

其他 stackoverflow 建议和任何其他外部文档都没有向我展示如何成功地将键绑定到函数。以下是我尝试过的链接(代码复制和粘贴)但没有成功。我看到很多人认为焦点是失败的原因,好像包含按钮的框架不是用户的目标,因此没有激活;然而,没有任何结果。以下是我尝试过的链接:

http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm

https://softwareengineering.stackexchange.com/questions/213935/why-use-classes-when-programming-a-tkinter-gui-in-python

python tkinter如何将键绑定到按钮

http://www.java2s.com/Code/Python/GUI-Tk/SetButtontogetfocus.htm

如何将按键绑定到 Tkinter 中的按钮

我在 PyCharm 5.0.4 中运行 Python 3.6。

上面链接中的代码是我一直在使用/修改的代码,以查看它是如何工作的,但没有一次尝试以执行操作而结束。我得到的最远的是一条错误消息。

谢谢。

编辑:我在下面使用的代码(来自最新链接)

from tkinter import *
root = Tk()

def LeftTurn(event):
    print('left')
frame=Frame(root, width=100, height=100)
frame.bind("<Left>", LeftTurn)   #Binds the "left" key to the frame and exexutes yourFunction if "left" key was pressed
frame.pack()


root.geometry("640x480")
root.title("Rover ")


root.mainloop()

我也试过这个(下)

from tkinter import *

root = Tk()

def yourFunction(event):
    print('left')

frame = Frame(root, width=100, height=100)

frame.bind("<Left>",yourFunction)   #Binds the "left" key to the frame and exexutes yourFunction if "left" key was pressed
frame.pack()

root.mainloop()

标签: pythonpython-3.xtkinter

解决方案


你是对的,这是一个焦点问题。用户不可能专注于框架,因此您要么必须通过添加

frame.focus()

或者您可以绑定到不会失焦的内容,例如根窗口:

root.bind("<Left>", LeftTurn) 

推荐阅读