How to Control a Mouse using Python

In order to control a mouse using Python, you may use the PyAutoGUI library.

You may then install the PyAutoGUI library using the following command (under Windows):

pip install pyautogui

Next, you’ll see the following 4 scenarios which demonstrate how to control a mouse using Python by:

  1. Moving a mouse cursor to a specific location
  2. Clicking on a specific location
  3. Double-clicking on a given location
  4. Moving a file to a folder

4 Scenarios of Controlling a Mouse using Python

Scenario 1: Moving a mouse cursor to a specific location

You can use the following syntax to move a mouse cursor to a specific location (note that you’ll need to specify the X and Y coordinates. The PyAutoGUI Documentation contains a simple Python program that would print the X and Y coordinates. Alternatively, you may use trial and error):

import pyautogui
pyautogui.moveTo(x_coordinate, y_coordinate)

Here is an example where both the X and Y coordinates are set to 50:

import pyautogui
pyautogui.moveTo(50, 50)

Scenario 2: Clicking on a specific location

In order to click (single-click) on a specific location, simply apply pyautogui.click based on your desired coordinates. For example:

import pyautogui
pyautogui.click(50, 50)

Scenario 3: Double-clicking on a given location

To double-click your desired location, simply set clicks=2:

import pyautogui
pyautogui.click(50, 50, clicks=2)

Scenario 4: Moving a file to a folder

To move a file into a folder, you may use a combination of moveTo and dragTo (where the dragTo is set for 2 seconds):

import pyautogui
pyautogui.moveTo(1400, 445)
pyautogui.dragTo(1700, 445, 2)

Finally, you may want to check the following guide that explains how to control a keyboard using Python.