修复按键重复 Python

我有一个等待按键并将它们记录在控制台中的脚本:


from pynput.keyboard import Key, Listener


def on_press(key):

    print('{0} pressed'.format(

        key))


def on_release(key):

    print('{0} release'.format(

        key))

    if key == Key.esc:

        # Stop listener

        return False


# Collect events until released

with Listener(

        on_press=on_press,

        on_release=on_release) as listener:

    listener.join()

系统本身可以工作,但是,当按住某个键时,它会产生以下结果:


Key.space pressed

Key.space pressed

Key.space pressed

Key.space pressed

Key.space pressed

Key.space pressed

Key.space pressed

Key.space pressed

Key.space pressed

如何使线程暂停,直到释放键?


繁星coding
浏览 122回答 2
2回答

噜噜哒

我们可以使用一个集合来检查当前正在按下哪个键。pressing_keys_set = set()def on_press(key):    if key not in pressing_keys_set:        print('{0} pressed'.format(key))        pressing_keys_set.add(key)def on_release(key):    print('{0} release'.format(key))    pressing_keys_set.remove(key)    if key == Key.esc:        # Stop listener        return False# Collect events until releasedwith Listener(    on_press=on_press,    on_release=on_release) as listener:    listener.join()

犯罪嫌疑人X

此代码必须帮助您from pynput.keyboard import Key, Listeneris_released=Falsedef on_press(key):    global is_released    if is_released:        print('{0} pressed'.format(key))        is_released=Falsedef on_release(key):    global is_released    print('{0} release'.format( key))    is_released=True    if key == Key.esc:        # Stop listener        return False# Collect events until releasedwith Listener(        on_press=on_press,        on_release=on_release) as listener:    listener.join()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python