Controlling mouse with Python

后端 未结 15 2145
滥情空心
滥情空心 2020-11-22 14:53

How does one control the mouse cursor in Python, i.e. move it to certain position and click, under Windows?

相关标签:
15条回答
  • 2020-11-22 15:32

    Try with the PyAutoGUI module. It's multiplatform.

    pip install pyautogui
    

    And so:

    import pyautogui
    pyautogui.click(100, 100)
    

    It also has other features:

    import pyautogui
    pyautogui.moveTo(100, 150)
    pyautogui.moveRel(0, 10)  # move mouse 10 pixels down
    pyautogui.dragTo(100, 150)
    pyautogui.dragRel(0, 10)  # drag mouse 10 pixels down
    

    This is much easier than going through all the win32con stuff.

    0 讨论(0)
  • 2020-11-22 15:34

    Quick and dirty function that'll left click wherever clicks times on Windows 7 using the ctypes library. No downloads required.

    import ctypes
    
    SetCursorPos = ctypes.windll.user32.SetCursorPos
    mouse_event = ctypes.windll.user32.mouse_event
    
    def left_click(x, y, clicks=1):
      SetCursorPos(x, y)
      for i in xrange(clicks):
       mouse_event(2, 0, 0, 0, 0)
       mouse_event(4, 0, 0, 0, 0)
    
    left_click(200, 200) #left clicks at 200, 200 on your screen. Was able to send 10k clicks instantly.
    
    0 讨论(0)
  • 2020-11-22 15:36

    The accepted answer worked for me but it was unstable (sometimes clicks wouldn't regsiter) so I added an additional MOUSEEVENTF_LEFTUP . Then it was working reliably

    import win32api, win32con
    def click(x,y):
        win32api.SetCursorPos((x,y))
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0) 
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
    click(10,10)
    
    0 讨论(0)
提交回复
热议问题