252

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

Max
  • 1,560
  • 14
  • 22
Sasha
  • 5,193
  • 8
  • 31
  • 31
  • 2
    Do you nee to make the mouse movement in code without user intervention? – rahul Jul 25 '09 at 07:19
  • More information would be *really* helpful... – Gabriel Hurley Jul 25 '09 at 07:20
  • I wotk in Windows and i don't use any toolkit. I am really new to Python and I never worked with any GUI before. Where I start from? What mannual should I read? – Sasha Jul 25 '09 at 07:26
  • 2
    why you need a python to do that, you can do that yourself? on a more serious note, why you need it, what is the purpose, a bit more details would be great – Anurag Uniyal Jul 25 '09 at 07:48
  • I recently learned Python on Windows. I started with the tutorials at docs.python.org which were very good. – Jeffrey Kemp Jul 25 '09 at 07:49
  • If you're trying the answer in a VirtualBox VM and it doesn't seem to work, try disabling mouse pointer integration. Thanks for the solution! – Ron E Mar 18 '12 at 03:30
  • 3
    Just FYI if you are using this to keep your machine from locking you could be violating your company or organizations security policy as it is a means of circumventing auto computer locking properties. Ive used this in some places no problem just always make sure to check with your Sys Admins. Ive seen people lose their jobs over minor things like this. – AlienAnarchist Mar 04 '16 at 15:37
  • I also needed keyboard simulation - [this answer](http://stackoverflow.com/a/2791979/957950) worked the best for me. – brichins Aug 04 '16 at 17:11

16 Answers16

361

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)
Twistios_Player
  • 100
  • 3
  • 11
Jeffrey Kemp
  • 57,730
  • 14
  • 106
  • 150
  • 15
    `win32api.SetCursorPos((x,y))` is better to be replaced by `win32api.mouse_event(win32con.MOUSEEVENTF_MOVE | win32con.MOUSEEVENTF_ABSOLUTE, int(x/SCREEN_WIDTH*65535.0), int(y/SCREEN_HEIGHT*65535.0))` in my experience for better integration with other application such as games. – Falcon May 31 '12 at 18:59
  • 1
    @ObsessiveSSOℲ just take off the MOUSEEVENTF_ABSOLUTE flag. for details: http://msdn.microsoft.com/en-us/library/windows/desktop/ms646260(v=vs.85).aspx – Falcon Dec 28 '12 at 17:14
  • can I use this library to control the speed/acceleration of the mouse ? – Someone Someoneelse Jun 05 '14 at 21:27
  • This had the advantage of not requiring installation (and associated management review and approval) of non-standard Python modules across 50+ windows boxes (digital signage kiosks). – brichins Aug 04 '16 at 17:27
  • 4
    tested in `python3.x` works too, feel free to edit the answer – WhatsThePoint May 08 '17 at 12:38
  • Any idea how to perform such task without the necessity of using external libraries/tools? – Jewenile Jul 22 '17 at 17:43
  • @Jewenile, if you consider pywin32 to be an "external library/tool", then no. – Jeffrey Kemp Jul 23 '17 at 05:12
  • It should be noted that this works only in the command line. I tried it in IDLE, and it did not work, while in the command line, it worked perfectly. – CtrlAltF2 Jun 17 '18 at 00:17
  • One of the benefits of this answer over [this one](https://stackoverflow.com/a/27046948/1014587) is `win32api` and `win32con` are installed by default in portable packages like WinPython. Quite useful when automating tasks on PCs you don't have admin access on. – Mast Jul 19 '19 at 11:44
194

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.

Aryan Beezadhur
  • 3,651
  • 3
  • 16
  • 39
Al Sweigart
  • 9,509
  • 9
  • 59
  • 85
  • 2
    For people trying to install pyautogui, look here https://stackoverflow.com/questions/5892297/problems-importing-python-xlib/18892493 and make sure to put sudo in front of your commands if you have permission problems. – retodaredevil Nov 15 '17 at 04:30
  • 20
    "PyAutoGUI is slow" because of a safety feature that adds a 0.1 second pause after each call. If your script is out of control, you can slam the mouse to the top-left corner in that 0.1 seconds to stop it. To disable this, run pyautogui.PAUSE = 0 (though this is not recommended, because you can't use the mouse/keyboard to stop the script.) – Al Sweigart Nov 24 '18 at 21:41
  • Also, PyAutoGUI does not play well with more than 1 monitors: https://github.com/asweigart/pyautogui/issues/162 – DimitrisMel Mar 16 '22 at 03:37
  • PyAutoGUI does work with multiple monitors on Windows (you use negative coordinates for other screens) but not yet on mac/linux. It also currently has no way of detecting the monitor layout. So, it works, but tenuously. – Al Sweigart Mar 19 '22 at 16:16
83

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
MattDMo
  • 96,286
  • 20
  • 232
  • 224
Anurag Uniyal
  • 81,711
  • 39
  • 167
  • 215
36

As of 2022, you can use mouse:

import mouse
mouse.move("500", "500")
mouse.click() # default to left click
# mouse.right_click()
# mouse.double_click(button='left')
# mouse.double_click(button='right')
# mouse.press(button='left')
# mouse.release(button='left')

Full Api documentation

Features

  • Global event hook on all mice devices (captures events regardless of focus).
  • Listen and sends mouse events.
  • Works with Windows and Linux (requires sudo).
  • Pure Python, no C modules to be compiled.
  • Zero dependencies. Trivial to install and deploy, just copy the files.
  • Python 2 and 3
  • Includes high level API (e.g. record and play).
  • Events automatically captured in separate thread, doesn't block main program.
  • Tested and documented.

Installation

  • Windows: pip install mouse
  • Linux: sudo pip install mouse
Pedro Lobito
  • 85,689
  • 29
  • 230
  • 253
27

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)
Gwen
  • 431
  • 1
  • 6
  • 11
24

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).

kenorb
  • 137,499
  • 74
  • 643
  • 694
Simon
  • 32,406
  • 17
  • 127
  • 196
  • 21
    A google for "Python controlling mouse movement" now finds this page, how meta. – Copas Feb 14 '12 at 15:45
  • 2
    For the sake of completeness, since the question also asked to simulate mouse clicks, I'll add : `Xlib.ext.xtest.fake_input(d, X.ButtonPress, 1); d.sync(); time.sleep(0.001); Xlib.ext.xtest.fake_input(d, X.ButtonRelease, 1); d.sync();` the sleep() call between press and release may or may not be required depending on the target application. – user336851 Jun 07 '13 at 19:00
  • 4
    @Copas - Results appearing in your Google mean nothing. You're in a bubble. This shows up in a DuckDuckGo search for the same term - that's something real. That's something everyone else can reproduce and see for themselves. That's meta. – ArtOfWarfare Aug 27 '14 at 13:28
  • 1
    To control mouse in a VNC session, you need the display number as well like "d = display.Display(':1')" where :1 is the display number. – Zafer Jan 07 '17 at 06:08
21

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

Fabio Varesano
  • 497
  • 6
  • 13
  • 8
    PyMouse has been superseded with [PyUserInput](https://github.com/SavinaRoja/PyUserInput), fits exactly the request, simple to use and cross platform. Big +1 – user336851 Jun 07 '13 at 18:53
  • @user336851, do you know how to `tap space` and `tap screen shot key` by using PyUswerInput? – user3768495 Jul 01 '15 at 23:55
  • @user336851, At this time `PyUserInput` is broken. Can't say if it works well or not because I can't even get it to install due to broken dependencies. – RattleyCooper Apr 01 '16 at 18:51
14

Pynput is the best solution I have found, both for Windows and for Mac. Super easy to program, and works very well.

For example,

from pynput.mouse import Button, Controller

mouse = Controller()

# Read pointer position
print('The current pointer position is {0}'.format(
    mouse.position))

# Set pointer position
mouse.position = (10, 20)
print('Now we have moved it to {0}'.format(
    mouse.position))

# Move pointer relative to current position
mouse.move(5, -5)

# Press and release
mouse.press(Button.left)
mouse.release(Button.left)

# Double click; this is different from pressing and releasing
# twice on Mac OSX
mouse.click(Button.left, 2)

# Scroll two steps down
mouse.scroll(0, 2)
Pro Q
  • 3,618
  • 3
  • 31
  • 74
  • I just tried to run an old program on a Windows computer and it did not work, so please do test it out before using. This program at least claims to support both. – Pro Q Feb 15 '18 at 06:24
  • I did some testing, and it turns out that my issue was that on Mac, having floats as coordinate values works just fine, but on Windows, the coordinates need to be integers. This module is cross-platform. – Pro Q Feb 25 '18 at 21:36
  • I have added an Issue to the github repository to see if they can improve it: https://github.com/moses-palmer/pynput/issues/79 – Pro Q Feb 25 '18 at 21:48
  • **It looks like the issue has since been fixed.** – Pro Q Oct 13 '18 at 21:38
13

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.
TankorSmash
  • 11,649
  • 6
  • 62
  • 103
4

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)
KoKlA
  • 749
  • 2
  • 8
  • 15
3

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

rockikz
  • 526
  • 1
  • 5
  • 16
2

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.

m02ph3u5
  • 2,837
  • 6
  • 38
  • 49
Destruktor_11
  • 175
  • 2
  • 14
  • You'll want to call `pyautogui.moveTo(x, y)` because `move()` moves the cursor relative to its current position. – Al Sweigart Jan 10 '20 at 03:59
  • Ah, sorry I misunderstood your original comment. Yes, both functions work. `moveTo()` moves to an absolute location, while `move()` moves relative to the current cursor location. – Al Sweigart Jan 11 '20 at 00:11
2

very easy 1- install pakage :

pip install mouse

2- add library to project :

import mouse

3- use it for example :

mouse.right_click()

in this url describe all function that you can use it :

https://github.com/boppreh/mouse

mamal
  • 1,279
  • 13
  • 11
  • It's even has MAC support now. Direct pip install will not work for MAC. You need to install in MAC by following commands: pip install pyobjc-framework-Quartz pip install git+https://github.com/boppreh/mouse.git – zafi005 Nov 05 '21 at 20:12
2

Move Mouse Randomly On Screen

It will move the mouse randomly on screen according to your screen resolution. check code below.

Install pip install pyautogui using this command.

import pyautogui
import time
import random as rnd

#calculate height and width of screen
w, h = list(pyautogui.size())[0], list(pyautogui.size())[1]

while True:
    time.sleep(1)
    #move mouse at random location in screen, change it to your preference
    pyautogui.moveTo(rnd.randrange(0, w), 
                     rnd.randrange(0, h))#, duration = 0.1)
Devil
  • 511
  • 6
  • 6
2

If you need to work with games. As explained in this post https://www.learncodebygaming.com/blog/pyautogui-not-working-use-directinput, some games like Minecraft or Fortnite have their own way of registering mouse / keyboard events. The way to control mouse and keyboard events is by using the brand new PyDirectInput library. Their github repository is https://github.com/learncodebygaming/pydirectinput, and has a lot of great information.
Here's a quick code that does a mouse loop, and clicks:

import pydirectinput  # pip install pydirectinput


pydirectinput.moveTo(0, 500)
pydirectinput.click()
Dr4kk0nnys
  • 532
  • 6
  • 10
2
import ctypes
from time import sleep

SetCursorPos = ctypes.windll.user32.SetCursorPos
print("Woohoo!\nTake Rest!\nMouse pointer will keep moving!\n\nPress ctrl+c to stop...!")
while True:
    SetCursorPos(300, 300)
    sleep(2)
    SetCursorPos(500, 500)
    sleep(4)
impika
  • 77
  • 2
  • 10