0

例如单击热键shifta并同时键入一个字符串并按回车键。是否应该在on_press方法中完成?

代码:

from pynput import keyboard
from pynput.mouse import Button, Controller

COMBINATIONS = [
    {keyboard.Key.shift, keyboard.KeyCode(char='a')}
]
current = set()

def execute():
    mouse = Controller()
    mouse.position = (550, 80)
    mouse.click(Button.left, 2)
    # keyboard = Controller()
    keyboard.type('google.com')
    # keyboard.press(keyboard.Key.enter)
    # keyboard.release(keyboard.Key.enter)

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

我收到以下错误:

AttributeError:模块“pynput.keyboard”没有属性“类型”

4

1 回答 1

0

每个mousekeyboard都有自己的Controller实例,因此您应该单独导入它们。像这样的东西:

from pynput import keyboard
from pynput.mouse import Button, Controller

COMBINATIONS = [
    {keyboard.Key.shift, keyboard.KeyCode(char='a')}
]
current = set()

def execute():
    mouse = Controller()
    mouse.position = (550, 80)
    mouse.click(Button.left, 2)
    keyboard_ctrl = keyboard.Controller()
    keyboard_ctrl.type('google.com')
    # keyboard_ctrl.press(keyboard.Key.enter)
    # keyboard_ctrl.release(keyboard.Key.enter)

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()
于 2019-04-18T11:16:09.597 回答