Tested on WinXP, Python 2.6 (3.x also tested) after installing pywin32 (pywin32-214.win32-py2.6.exe in my case):
import win32api, win32con
def click(x,y):
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
click(10,10)
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.
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
As of 2021, you can use mouse:
import mouse
mouse.move("500", "500")
mouse.left_click()
Features
Installation
pip install mouse
sudo pip install mouse
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With