Python 使用键盘模块检测按键事件

Python keypress event detection using keyboard module

我使用键盘模块为代码实现按键事件检测器。我需要在 for 循环内的 while 循环内检测按键事件。代码如下

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

按一次space键后输出显示:

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!

我希望它只在按键被按下时检测。 is_pressed 一旦按键被按下,它就永远设置为真。有没有其他方法让它只检测一次并将 is_pressed 重置为 false?

如果在每次检查按下的键之间引入大约 0.2 秒的延迟,则以下代码有效。

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
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