pynput doesn't work as intended regarding mouse clicking and button pressing

情到浓时终转凉″ 提交于 2020-07-20 03:49:30

问题


My goal is to run different codes with various hotkeys. I'm using pynput. The problem is that the script doesn't work normally. The code is as follows:

import pynput, pyperclip, re, time

mouse = pynput.mouse.Controller()
keyboard = pynput.keyboard.Controller()

def on_activate_h():
    mouse.position = (500, 500)
    mouse.click(pynput.mouse.Button.left, 1)
    time.sleep(1)
    mouse.position = (600, 600)
    mouse.click(pynput.mouse.Button.left, 1)
    time.sleep(1)
    mouse.position = (800, 800)
    mouse.click(pynput.mouse.Button.left, 1)
    print('<ctrl>+<alt>+h pressed')

def on_activate_i():
    mouse.position = (300, 300)
    mouse.click(pynput.mouse.Button.left, 1)
    with keyboard.pressed(pynput.keyboard.Key.ctrl):
        keyboard.press('a')
        keyboard.release('a')
    with keyboard.pressed(pynput.keyboard.Key.ctrl):
        keyboard.press('c')
        keyboard.release('c')

    sourceStr = pyperclip.paste()
    sourceStr = re.sub(r'a', r'A', sourceStr)

    pyperclip.copy(sourceStr)
    with keyboard.pressed(pynput.keyboard.Key.ctrl):
        keyboard.press('v')
        keyboard.release('v')
    print('<ctrl>+<alt>+i pressed')

with pynput.keyboard.GlobalHotKeys({
        '<ctrl>+<alt>+h': on_activate_h,
        '<ctrl>+<alt>+i': on_activate_i}) as h:
    h.join()

There are several problems:

  1. Hotkey problems - When pressing Ctrl+Alt (not Ctrl+Alt+h/i), the script starts running. Or, not every hotkey combos works. It works every other time when the Ctrl+Alt+h/i is pressed.
  2. Mouse problem - The mouse doesn't click at the specified position. It often clicks in the top right part of the screen, whereas the specified positions are in the bottom left part of the screen.
  3. Key pressing problem - As you can see in the code, I intend to get content from the clipboard, processing it with Regex, and paste the result to clipboard. First, it can't get the correct content from clipboard. It gets contents like "vvvvv'. Sencond, the Regex doesn't always replace 'a' with 'A'. The result is like 'vvvvva' or 'vvvvvA'.

I'm sure the culprit is pynput. But I don't know why.

来源:https://stackoverflow.com/questions/61764725/pynput-doesnt-work-as-intended-regarding-mouse-clicking-and-button-pressing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!