点击热键,例如 shift a ,同时键入一个字符串,然后按Enter键。应该用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'没有属性'type'
答案 0 :(得分:0)
每个mouse
和keyboard
都有自己的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()