简体   繁体   中英

Binding key presses

I'm currently working on project where I ssh to a raspberry pi from my laptop to control some motors. I have written some code in Python that allows you to enter a letter and depending on the letter it moves forwards or backwards. However you have to press enter after every letter for the code to execute. Is there a way that the interface detects letters without the need to press enter. I know you can bind key presses in tkinter but I can not do that through ssh. Thanks in advance

You could use the curses library for that.

You can grab the key that was pressed using the screen.getch() function. It will return the decimal code of the key (see ASCII Table ).

An example:

import curses


screen = curses.initscr()
curses.cbreak()
screen.keypad(1)

key = ''

while key != ord('q'):  # press <Q> to exit the program
    key = screen.getch()  # get the key
    screen.addch(0, 0, key)  # display it on the screen
    screen.refresh()

    # the same, but for <Up> and <Down> keys:
    if key == curses.KEY_UP:
        screen.addstr(0, 0, "Up")
    elif key == curses.KEY_DOWN:
        screen.addstr(0, 0, "Down")

curses.endwin()

Another option is sshkeyboard library. Simply pip install sshkeyboard , and then use the following code to detect key presses over SSH:

from sshkeyboard import listen_keyboard

def press(key):
    print(f"'{key}' pressed")

def release(key):
    print(f"'{key}' released")

listen_keyboard(
    on_press=press,
    on_release=release,
)

Inside def press you could have some logic to react to specific keys:

def press(key):
    if key == "up":
        print("up pressed")
    elif key == "down":
        print("down pressed")
    elif key == "left":
        print("left pressed")
    elif key == "right":
        print("right pressed")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM