The PyAutoGUI library can be used to control a mouse in Python.
To install the PyAutoGUI library:
pip install pyautogui
Next, you’ll see 4 scenarios to control a mouse in Python by:
- Moving a mouse cursor to a specific location
- Clicking on a specific location
- Double-clicking on a given location
- Moving a file to a folder
4 Scenarios of Controlling a Mouse using Python
Scenario 1: Moving a mouse cursor to a specific location
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 to 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 on 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, 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, check the following guide that explains how to control a keyboard using Python.