Pynput 用于测试是否按下 ctrl、shift 或 alt

问题描述 投票:0回答:1

Pynput 有没有办法测试在 òn_pressedon_release 处理程序中是否按下了 ctrl、shift 或 alt

python-3.x pynput
1个回答
0
投票

[如果我们参考这里的 pynput 文档,我们就可以做:-

def on_press(key):
    if key == keyboard.Key.ctrl:
        print("Ctrl key pressed")
    elif key == keyboard.Key.shift:
        print("Shift key pressed")
    elif key == keyboard.Key.alt:
        print("Alt key pressed")
def on_release(key):
    if key == keyboard.Key.esc:
        # Stop listener
        return False
# Collect events until released
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

或者如果您希望甚至可以将键存储在字典中以便像这样迭代:-

COMBINATION = {keyboard.Key.ctrl, keyboard.Key.shift, keyboard.Key.alt}
] 1

在上面提供的示例中,我们使用 pynput.keyboard.Listener 来检查 òn_pressed 或 on_release 处理程序中是否按下了 ctrl、shift 或 alt

另一种方法是使用 pynput.keyboard.Controller

[这是我们可以做的:-

alt_pressed

Whether any alt key is pressed.

Please note that this reflects only the internal state of this controller. See modifiers for more information.

ctrl_pressed

Whether any ctrl key is pressed.

Please note that this reflects only the internal state of this controller. See modifiers for more information.

shift_按下

Whether any shift key is pressed, or caps lock is toggled.

Please note that this reflects only the internal state of this controller. See modifiers for more information.

因此我们可以简单地使用这些函数:-

kb = keyboard.Controller()
if kb.ctrl_pressed:
    print("Ctrl key is pressed")
if kb.shift_pressed:
    print("Shift key is pressed")
if kb.alt_pressed:
    print("Alt key is pressed")
print(f"Key pressed: {key.char}")

]2

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.