如何将按键绑定到 Tkinter 中的按钮 [英] How to bind a keypress to a button in Tkinter

查看:92
本文介绍了如何将按键绑定到 Tkinter 中的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的高级项目涉及一个我可以通过 wifi 控制的机器人.我正在使用 Raspberry Pi 和 Tkinter 窗口向机器人发送命令.我有我的 Tkinter 窗口的草稿,但我想知道是否有办法将按钮按下绑定到箭头键.这样我就可以通过使用箭头键而不是点击每个按钮来控制机器人.这是我的代码,我需要添加什么?

My Senior Project involves a robot I can control over wifi. I am using a Raspberry Pi and a Tkinter window to send commands to the robot. I have the rough draft of my Tkinter window, but I am wondering if there is a way to bind the button press to the arrow keys. That way I can control the robot by using my arrow keys rather than clicking on each button. Here is my code, what would I have to add?

代码:

from Tkinter import *


message = ""

class App:

    def __init__(self, master):

        frame=Frame(master)
        frame.grid()

        status = Label(master, text=message)
        status.grid(row = 0, column = 0)

        self.leftButton = Button(frame, text="<", command=self.leftTurn)
        self.leftButton.grid(row = 1, column = 1)

        self.rightButton = Button(frame, text=">", command=self.rightTurn)
        self.rightButton.grid(row = 1, column = 3)

        self.upButton = Button(frame, text="^", command=self.upTurn)
        self.upButton.grid(row = 0, column = 2)

        self.downButton = Button(frame, text="V", command=self.downTurn)
        self.downButton.grid(row=2, column = 2)

    def leftTurn(self):
        message = "Left"
        print message

    def rightTurn(self):
        message = "Right"
    print message

    def upTurn(self):
        message = "Up"
        print message

    def downTurn(self):
        message = "Down"
        print message



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

app = App(root)

root.mainloop()

推荐答案

我相信你想要的是将按键绑定到框架/功能.Tkinter 内置了自己的事件和绑定处理,您可以在 此处阅读一>.

I believe what you want is to bind the key press to the frame/function. Tkinter has its own event and binding handling built in which you can read up on here.

这是您应该能够调整您的程序的快速示例.

Here is quick example which you should be able to adapt your program.

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()

这篇关于如何将按键绑定到 Tkinter 中的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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