简体   繁体   中英

How to use keyboard event as part of a conditional statement

I'm trying to make a program that outputs a key press event as a response to another keyboard event. How do I get it to use the particular value of the key pressed in a conditional statement? The codes I try seem to be skipping the conditional statement altogether.

Initially tried [if key == '1':], then tired by [if key == 1:] . Also tried various means of assigning [key] to a variable. Also tried [print('2')] instead of using [pyautogui.typewrite('2')] . Tried putting the code both in on_press(key) and in on_release(key).

`

    import pyautogui
    from pynput.keyboard import Key, Listener

    def on_press(key):
        print('{0} pressed'.format(key))

    def on_release(key):
        print('{0} release'.format(key))
        k = format(key)
        if k == '1':       #THIS IS THE PART I CAN'T GET TO WORK
            pyautogui.typewrite('2', 0.5)
        if key == Key.esc:
    # Stop listener
            return False
    # Collect events until released
    with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

`

Expected to output '2' whenever I press '1' on the keyboard(in addition to the output of the keypress and keyrelease event). The output for the pressing of '1' doesn't work.

You can use keyboard library, in order to handle/create key events.

while True:  
    try: 
        if keyboard.is_pressed('1'):   
            print('{} is pressed'.format(1))
            break
        else:
            pass
    except:
        break 

the above code runs until 1 is received as a keypress. Upon pressing the key, 1 is pressed will be printed.

You can further use other functions of this library, in order to detect a key down even too.

The key parameter that your on_press / on_release receives is not the character string but rather a Key/KeyChar object, that's why you can't compare it directly with a string.

To access the keyboard input character, use key.char instead:

def on_press(key): 
    print("pressed '{}'".format(key.char))

Look at the example codes on pynput's documentation on how to capture non letter keys .

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