检测Python中的按键,每次迭代可能需要超过几秒钟?

2023-11-27

Edit:使用以下答案Keyboard.on_press(回调,抑制= False)在ubuntu下工作正常,没有任何问题。 但在红帽/亚马逊 Linux,它无法工作。

我已经使用了这里的代码片段thread

import keyboard  # using module keyboard
while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        if keyboard.is_pressed('q'):  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
    except:
        break  # if user pressed a key other than the given key the loop will break

但上面的代码要求每次迭代都在纳秒内执行。在以下情况下会失败:

import keyboard  # using module keyboard
import time
while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        print("sleeping")
        time.sleep(5)
        print("slept")
        if keyboard.is_pressed('q'):  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
    except:
        print("#######")
        break  # if user pressed a key other than the given key the loop will break

您可以使用事件处理程序keyboard模块以达到预期的结果。

此类处理程序之一是keyboard.on_press(callback, suppress=False): 它为每个调用回调key_down事件。 您可以参考更多信息键盘文档

这是您可以尝试的代码:

import keyboard  # using module keyboard
import time

stop = False
def onkeypress(event):
    global stop
    if event.name == 'q':
        stop = True

# ---------> hook event handler
keyboard.on_press(onkeypress)
# --------->

while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        print("sleeping")
        time.sleep(5)
        print("slept")
        if stop:  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
    except:
        print("#######")
        break  # if user pressed a key other than the given key the loop will break
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

检测Python中的按键,每次迭代可能需要超过几秒钟? 的相关文章

随机推荐