1

I used keyboard module to implement a keypress event detector for a code. I need to detect the keypress event inside a while loop inside a for loop. The code is as follows

import keyboard

for i in range(5):
    loop = True
    while loop:
        if keyboard.is_pressed("space"):
            print("Iteration: {}\tSpace key pressed!".format(i))
            loop = False

The output shows after pressing space key once:

Iteration: 0    Space key pressed!
Iteration: 1    Space key pressed!
Iteration: 2    Space key pressed!
Iteration: 3    Space key pressed!
Iteration: 4    Space key pressed!

I want it to detect only when the key is pressed. is_pressed sets it to true forever once the key is pressed. Is there any other way to get it detected only once and reset the is_pressed to false?

2 Answers 2

1
import keyboard
import time

yes = 1
delay = 0.2 # or >= 0.2 secs works fine

for i in range(5):
    loop = True
    while loop:
        if keyboard.is_pressed("space"):
            if yes = 1:
                yes = 0
                print("Iteration: {}\tSpace key pressed!".format(i))
                loop = False
        else:
            yes = 1
Sign up to request clarification or add additional context in comments.

Comments

1

Following code works if you introduce some delay, of ~0.2 secs, between each check of key being pressed.

import keyboard
import time

delay = 0.2 # or >= 0.2 secs works fine

for i in range(5):
    loop = True
    while loop:
        if keyboard.is_pressed("space"):
            print("Iteration: {}\tSpace key pressed!".format(i))
            loop = False
            time.sleep(delay) # adding delay between each checks

1 Comment

It worked for me even with a delay of 0.1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.