Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
797 views
in Technique[技术] by (71.8m points)

python - How to bind a keypress to a button in 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?

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...