Python Keyboard Library is unable to differentiate between 'down' and 'right+down'

88 Views Asked by At

This is my code:

import keyboard as kb

def key_selected():
    if kb.is_pressed('shift+s+down'):
        return 'True1' 
    
    elif kb.is_pressed('shift+s+right+down'):
        return 'True2'
    
    else:
        return 'NOTHING' 

while True:
    x = key_selected()
    print(x)

It returns True1 even when I press 'shift+s+right+down'. How can resolve this?

1

There are 1 best solutions below

2
On BEST ANSWER

The thing with elif is that the condition is tested only if the previous conditions were False. So when you press shift + s + down + right, if kb.is_pressed('shift+s+down') is triggered because you have pressed shift and s and down, and the elif is ignored.

If you reverse the order so that you check for the more specific condition first, it should work just fine.

def key_selected():
    if kb.is_pressed('shift+s+right+down'):
        return 'True2' 
    
    elif kb.is_pressed('shift+s+down'):
        return 'True1'
    
    else:
        return 'NOTHING'

does what you expect.