我正在写一段非常简单的代码。
这是我的代码,在按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()
答案 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()