【发布时间】:2018-11-02 19:46:50
【问题描述】:
没有其他 stackoverflow 建议,也没有任何其他外部文档向我展示了如何成功地将键绑定到函数。以下是我尝试过的链接(代码复制和粘贴)但没有运气。我看到很多人认为焦点是失败的原因,好像包含按钮的框架不是用户的目标,因此没有激活;然而,没有任何结果。以下是我尝试过的链接:
http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm
python tkinter how to bind key to a button
http://www.java2s.com/Code/Python/GUI-Tk/SetButtontogetfocus.htm
How to bind a keypress to a button in 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()
【问题讨论】:
-
请发布您的代码。
-
向我们展示您尝试过的minimal reproducible example 及其产生的错误消息。
-
看,问题是:当我尝试时它会起作用。所以我们真的需要看看你的代码。
-
我发布了我尝试的代码,是否可以评论你到底使用了什么?
-
焦点在窗口或像Entry、Text和其他可以与鼠标或键盘交互的小部件上。
标签: python python-3.x tkinter