0

我正在尝试重新映射结合 pynput 和 pyautogui 的快捷方式,但出现错误

在使用keyboard.pressed(Key.shift)执行时:AttributeError:模块'pynput.keyboard'没有属性'pressed'

from pynput import keyboard
import pyautogui

# The key combination to check
COMBINATIONS = [
    {keyboard.Key.ctrl, keyboard.KeyCode(char='z')},
    {keyboard.Key.ctrl, keyboard.KeyCode(char='x')}
]

# The currently active modifiers
current = set()

def execute():
    pyautogui.typewrite('Hello world!\n', interval=secs_between_keys)
    #pyautogui.hotkey('cmd', 'v')

def on_press(key):
    if any([key in COMBO for COMBO in COMBINATIONS]):
        current.add(key)
        if any(all(k in current for k in COMBO) for COMBO in COMBINATIONS):
            execute()

def on_release(key):
    if any([key in COMBO for COMBO in COMBINATIONS]):
        current.remove(key)

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

我是一个初学者,不知道为什么我不能在这里使用 pyautogui 函数。你能开导我吗?非常感谢!

4

2 回答 2

0

你想要presswhich 接受key论点,而不是pressed.

来自文档:-

Controller.press(key)
Presses a key.

A key may be either a string of length 1, one of the Key members or a KeyCode.
于 2019-03-12T13:01:22.577 回答
0

这是一个使用 pynput 的完整且经过测试的示例:

from pynput import keyboard

# The key combination to check
COMBINATIONS = [
    {keyboard.Key.ctrl_l, keyboard.KeyCode(char='z')},
    {keyboard.Key.ctrl_r, keyboard.KeyCode(char='z')},    
    {keyboard.Key.ctrl_l, keyboard.KeyCode(char='x')},    
    {keyboard.Key.ctrl_r, keyboard.KeyCode(char='x')}
]

# The currently active modifiers
current = set()

def execute():
    print("Here I am")

def on_press(key):
    if any([key in COMBO for COMBO in COMBINATIONS]):
        current.add(key)
        if any(all(k in current for k in COMBO) for COMBO in COMBINATIONS):
            execute()

def on_release(key):
    if any([key in COMBO for COMBO in COMBINATIONS]):
        current.remove(key)

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

在我看来,主要问题与使用操作系统或其他应用程序使用的特定组合键(例如 Control + C)有关。

于 2019-03-12T12:58:10.100 回答