How to bind a keypress to a button in Tkinter

旧时模样 提交于 2019-12-18 05:28:08

问题


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?

Code:

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

回答1:


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


来源:https://stackoverflow.com/questions/20832909/how-to-bind-a-keypress-to-a-button-in-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!