Controlling mouse with Python

后端 未结 15 2146
滥情空心
滥情空心 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:18

    If you want to move the mouse, use this:

    import pyautogui
    pyautogui.moveTo(x,y)
    

    If you want to click, use this:

    import pyautogui
    pyautogui.click(x,y)
    

    If you don't have pyautogui installed, you must have python attached to CMD. Go to CMD and write: pip install pyautogui

    This will install pyautogui for Python 2.x.

    For Python 3.x, you will probably have to use pip3 install pyautogui or python3 -m pip install pyautogui.

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

    Another option is to use the cross-platform AutoPy package. This package has two different options for moving the mouse:

    This code snippet will instantly move the cursor to position (200,200):

    import autopy
    autopy.mouse.move(200,200)
    

    If you instead want the cursor to visibly move across the screen to a given location, you can use the smooth_move command:

    import autopy
    autopy.mouse.smooth_move(200,200)
    
    0 讨论(0)
  • 2020-11-22 15:20

    Check out the cross platform PyMouse: https://github.com/pepijndevos/PyMouse/

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

    Linux

    from Xlib import X, display
    d = display.Display()
    s = d.screen()
    root = s.root
    root.warp_pointer(300,300)
    d.sync()
    

    Source: Python mouse move in 5 lines of code (Linux only).

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

    You can use win32api or ctypes module to use win32 apis for controlling mouse or any gui

    Here is a fun example to control mouse using win32api:

    import win32api
    import time
    import math
    
    for i in range(500):
        x = int(500+math.sin(math.pi*i/100)*500)
        y = int(500+math.cos(i)*100)
        win32api.SetCursorPos((x,y))
        time.sleep(.01)
    

    A click using ctypes:

    import ctypes
    
    # see http://msdn.microsoft.com/en-us/library/ms646260(VS.85).aspx for details
    ctypes.windll.user32.SetCursorPos(100, 20)
    ctypes.windll.user32.mouse_event(2, 0, 0, 0,0) # left down
    ctypes.windll.user32.mouse_event(4, 0, 0, 0,0) # left up
    
    0 讨论(0)
  • 2020-11-22 15:28

    Another alternative would be mouse library, I personally use it as it is relatively simple and cross-platform.

    Here is how you can use it:

    import mouse
    # move 100 right and 100 down with a duration of 0.5 seconds
    mouse.move(100, 100, absolute=False, duration=0.5)
    # left click
    mouse.click('left')
    # right click
    mouse.click('right')
    

    Here is the source: How to Control your Mouse in Python

    0 讨论(0)
提交回复
热议问题