如何避免在“ on_press”侦听器事件上循环?

时间:2019-12-20 19:42:27

标签: python listener pynput onpress

我正在写一段非常简单的代码。

  • 我想听键盘。
  • 当我按F11键时,必须仅显示一次消息“已激活...”。
  • 当我再次按F11时,必须同时显示一次消息“已停用...”。
  • 依此类推...
  • 当我按F12键时,我希望收听者停止播放。

这是我的代码,在按F11键时,我很难找到正确的实现方式来避免常量循环(“已激活...已停用...已激活...已停用...”)。 / p>

此外,欢迎提供更好的实现,更多的最新技术,更多的pythonic的建议!

# -*- coding: utf-8 -*-

from pynput import keyboard

is_active = False

def on_press(key):
    global is_active
    # Activate/Deactivate when pressing F11
    if key == keyboard.Key.f11:
        if is_active:
            is_active = False
            print("Deactivate...")
        else:
            is_active = True
            print("Activate...")
    # Stop "on_press" listener
    if key == keyboard.Key.f12:
        return False

with keyboard.Listener(on_press=on_press) as listener:
    listener.join()

1 个答案:

答案 0 :(得分:0)

您将要使用

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

按下某个键时,您将获得多个事件,就像您按住aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa键一样,您将获得多个事件。您需要设置一种锁定机制,在首次按下该锁定机制之前,您不要松开它,直到释放钥匙为止。

修改后的代码:

# -*- coding: utf-8 -*-

from pynput import keyboard

is_active = False
is_f11_pressed = False

def on_press(key):
    global is_f11_pressed
    global is_active
    # Activate/Deactivate when pressing F11
    if key == keyboard.Key.f11 and not is_f11_pressed:
        is_f11_pressed = True
        if is_active:
            is_active = False
            print("Deactivate...")
        else:
            is_active = True
            print("Activate...")
    # Stop "on_press" listener
    if key == keyboard.Key.f12:
        return False

def on_release(key):
    global is_f11_pressed
    if key == keyboard.Key.f11:
        is_f11_pressed = False

with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()