Skip to content
Advertisement

Detect key release while using keyboard module

Warning: my English sucks and also I’m really new to python
So I’m making a program that requires a specific Key Press (e.g. space bar) to continue the loop, like:

for i in *some sort of list*: 
    print(something)
    *waits for a key*

and my method for the last line is the keyboard module (not from pynput), which has the functionis_pressed. When I pressed a key, I got the output:

*something*
*something*
*something*
*repeats for several times*

I know that the function detects key press instead of press and release, so this output stops as soon as I release it. But that not how my program works. It should respond every time I release that key. Unfortunately I couldn’t find a function called is_released or something, and module pynput can’t get the key I pressed using Listener. At least I can’t.

Also, is there a way to have both keyboard and pynput importable in a computer? My VS Code ignores keyboard when pynput is installed.

Edit: this is my solution for the problem, but it’s super dumb:

while True:
    if keyboard.is_pressed('space'):
        while True:
            if not keyboard.is_pressed('space'):
                break
        break

Is there a function that does the same thing?

Advertisement

Answer

Since it detects keypress only, use flags. I think something like this can do it: 1. Make a bool variable to detect a single key press 2. If key is pressed, the bool will be set to true 3. If bool is true and not key.is_pressed: do your thing 4. Set bool to false after operation

For example, in code, that will be like this:

keypress = False
key = 'space'
while True:
    if keypress and not keyboard.is_pressed(key):
        '''DO YOUR THING'''
        #beak out of while loop?
        keypress = False
        break
    elif keyboard.is_pressed(key) and not keypress:
        keypress = True

Dont know if this is how you’ll do it, but I guess you can get my drift from this. Good luck!

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement