【问题标题】:How to listen letter keys with combination of modifier keys using pynput?如何使用pynput收听带有修饰键组合的字母键?
【发布时间】:2020-04-18 19:43:47
【问题描述】:

我正在尝试使用 python 自动化一些东西。我使用 pynput 来监听组合键。我正在尝试听 ctrl+shift+alt 的组合。我对修饰键没有问题,但只有字母键。我查看了 python 文档页面并尝试了以下操作:

from pynput import keyboard
from subprocess import Popen, PIPE
from evdev import uinput, ecodes as e
import os

# The key combination to check
COMBINATION = {keyboard.Key.shift, keyboard.Key.ctrl, keyboard.Key.alt, keyboard.KeyCode.from_char('k')}

# The currently active modifiers
current = set()

def on_press(key):
    if key in COMBINATION:
        current.add(key)
        if all(k in current for k in COMBINATION):
            print("x")
    if key == keyboard.Key.esc:
        listener.stop()

def on_release(key):
    try:
        current.remove(key)
    except KeyError:
        pass

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

从终端运行 python 文件后,脚本无法检测到我的组合键。

【问题讨论】:

    标签: python pynput


    【解决方案1】:

    从文档中,您可以使用此方法。 https://pynput.readthedocs.io/en/latest/keyboard.html

    from pynput import keyboard
    
    def on_activate():
        print('Global hotkey activated!')
    
    def for_canonical(f):
        return lambda k: f(l.canonical(k))
    
    hotkey = keyboard.HotKey(
        keyboard.HotKey.parse('<ctrl>+<alt>+h'),
        on_activate)
    with keyboard.Listener(
            on_press=for_canonical(hotkey.press),
            on_release=for_canonical(hotkey.release)) as l:
        l.join()
    

    【讨论】:

    • 我已经看到了,但是在这段代码 sn-p 中我看不到任何关于字母键的信息。谢谢。
    • 这就是我找了好几个小时的答案!谢谢,这完美! :D
    • 对我来说,这感觉像是一种懒惰的贡献,没有真正花时间考虑 op 的需求和代码。这只是文档的复制粘贴,没有上述内容,也没有解释为什么它适用于 OPs 问题。
    猜你喜欢
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2021-02-11
    • 1970-01-01
    • 2022-01-02
    相关资源
    最近更新 更多