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

2024-04-26 05:24:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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

代码:

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

Tags: textselfmastermessagetkinterdef机器人column
1条回答
网友
1楼 · 发布于 2024-04-26 05:24:34

我相信你想要的是将按键绑定到框架/功能。Tkinter有自己的事件和绑定处理,您可以在其中读取here

这里有一个快速的例子,你应该能够调整你的程序。

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

相关问题 更多 >