重新映射我的组合pyautogui和pynput的快捷方式

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

我正在尝试重新映射组合pynput和pyautogui的快捷方式,但我收到了错误

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

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功能。你能好好开导我吗?非常感谢!

python hotkeys pyautogui pynput
2个回答
0
投票

你想要press采用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.

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()

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

© www.soinside.com 2019 - 2024. All rights reserved.