python - 如何添加键绑定?
问题描述
其他 stackoverflow 建议和任何其他外部文档都没有向我展示如何成功地将键绑定到函数。以下是我尝试过的链接(代码复制和粘贴)但没有成功。我看到很多人认为焦点是失败的原因,好像包含按钮的框架不是用户的目标,因此没有激活;然而,没有任何结果。以下是我尝试过的链接:
http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm
http://www.java2s.com/Code/Python/GUI-Tk/SetButtontogetfocus.htm
我在 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()
解决方案
你是对的,这是一个焦点问题。用户不可能专注于框架,因此您要么必须通过添加
frame.focus()
或者您可以绑定到不会失焦的内容,例如根窗口:
root.bind("<Left>", LeftTurn)
推荐阅读
- django - 从 ManyToManyField 填充 MultipleChoiceField 值
- python - 如何在同一行打印这些字符?
- python - 将单词传递给函数
- c# - `Clicked` 和 `Command` 在同一个 Xamarin 视图上使用时如何工作?
- laravel - 如何将 PHPMailer 连接转换为 Laravel .env?
- excel - PowerShell - Import Excel then Export CSV without using Excel or COM
- machine-learning - 通过了解一些未来事件来增强预测
- javascript - 从 JSON 响应中删除属性
- mysql - 在这种情况下如何对 COUNT() 求和
- python-3.x - 在多个键上合并 pandas ojn 2 数据帧