简体   繁体   English

keyboard.is_pressed() 无法正常工作

[英]keyboard.is_pressed() Not working properly

I have some simple code to print "Hello" when I press my "ctrl" (control) key.当我按下“ctrl”(控制)键时,我有一些简单的代码可以打印“Hello”。 Here is the code:这是代码:

while(True):
    if keyboard.is_pressed('ctrl'):
        print("Hello")

This works but when I press my control key it prints 16 times instead of once.这可行,但是当我按下控制键时,它会打印 16 次而不是一次。 I tried using 'keyboard.read_key() == 'ctrl' but I got the same issue.我尝试使用 'keyboard.read_key() == 'ctrl' 但我遇到了同样的问题。

It is because the while is having no delay and the process keep entering in to the while loop.这是因为while没有延迟,进程不断进入while循环。 Although, the key press is just one from the user's perspective yet the computer is actually seeing multiple presses of those due to the while loop.虽然从用户的角度来看,按键只是一个按键,但由于while循环,计算机实际上会看到多次按键。

I am not sure how to effectively verify this but if we press the key just once and add a delay as below, we'll be able observe the difference:我不确定如何有效地验证这一点,但如果我们只按一次键并添加如下延迟,我们将能够观察到差异:

import keyboard
import time
while(True):
    if keyboard.is_pressed('ctrl'):
        print("Hello")
        time.sleep(1)

I like to use the following logic:我喜欢使用以下逻辑:

if keyboard.is_pressed('ctrl'):
    keyboard.release('ctrl')
    time.sleep(0.1)
    """Do something"""

Depending on the application, you may need to make sure that the key is released before continuing, keyboard.release() comes in handy.根据应用程序,您可能需要确保在继续之前释放键, keyboard.release()会派上用场。 I also agree with @KrishnaChaurasia that a delay must be added to make sure that the computer does not perform many cycles in what humans perceive as an instant.我也同意@KrishnaChaurasia 的观点,即必须添加延迟以确保计算机不会在人类感知的瞬间执行许多循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM