How to control a mouse with Python?

Sometimes, we want to control a mouse with Python.

In this article, we’ll look at how to control a mouse with Python.

How to control a mouse with Python?

To control a mouse with Python, we can use the pyautogui package.

To install it, we run

pip install pyautogui

Then we use it with

import pyautogui

pyautogui.click(100, 100)

pyautogui.moveTo(100, 150)
pyautogui.moveRel(0, 10)
pyautogui.dragTo(100, 150)
pyautogui.dragRel(0, 10)

to call click to click on the location with the given x-y screen coordinates.

We call moveTo to move to the given screen coordinates.

moveRel moves relative to the current position.

dragTo drags the mouse to the given screen coordinates.

dragRel drags the mouse to screen coordinates relative to the current coordinates.

Conclusion

To control a mouse with Python, we can use the pyautogui package.