How does one control the mouse cursor in Python, i.e. move it to certain position and click, under Windows?
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
.
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)
Check out the cross platform PyMouse: https://github.com/pepijndevos/PyMouse/
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).
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
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