Use Mouse to Draw in Python: A Simple Guide

In this tutorial, we will introduce how to draw by moving mouse in python. We will use python pyautogui to implement it.

Python pyautogui

pyautogui package can make us draw easily in python. Here is some basic usage for it.

>>> import pyautogui
>>> screenWidth, screenHeight = pyautogui.size() # Get the size of the primary monitor.

>>> currentMouseX, currentMouseY = pyautogui.position() # Get the XY position of the mouse.

>>> pyautogui.moveTo(100, 150) # Move the mouse to XY coordinates.

>>> # Click the mouse.
>>>, 200) # Move the mouse to XY coordinates and click it.
>>>'button.png') # Find where button.png appears on the screen and click it.

>>> pyautogui.move(0, 10) # Move mouse 10 pixels down from its current position.
>>> pyautogui.doubleClick() # Double click the mouse.
>>> pyautogui.moveTo(500, 500, duration=2, tween=pyautogui.easeInOutQuad) # Use tweening/easing function to move mouse over 2 seconds.

>>> pyautogui.write('Hello world!', interval=0.25) # type with quarter-second pause in between each key
>>>'esc') # Press the Esc key. All key names are in pyautogui.KEY_NAMES

>>> pyautogui.keyDown('shift') # Press the Shift key down and hold it.
>>>['left', 'left', 'left', 'left']) # Press the left arrow key 4 times.
>>> pyautogui.keyUp('shift') # Let go of the Shift key.

>>> pyautogui.hotkey('ctrl', 'c') # Press the Ctrl-C hotkey combination.

>>> pyautogui.alert('This is the message to display.') # Make an alert box appear and pause the program until OK is clicked.

In this article, we will use an example to show you how to use it to draw by mouse.

How to draw by moving mouse in python

We will introduce how to do step by step.

Step 1: install pyautogui

We can use pip to install

pip install pyautogui

Step 2: draw by moving mouse

Here is the full example code.

import pyautogui
import time

# time to change tabs from editor to paint;

# it will remain clicked till program ends;

# can be varied according to convininence
distance = 250

while distance > 0:
    # right
    pyautogui.dragRel(distance, 0, duration = 0.1)
    distance -= 5

    # down
    pyautogui.dragRel(0, distance, duration = 0.1)

    # left
    pyautogui.dragRel(-distance, 0, duration = 0.1)

    distance -= 5

    pyautogui.dragRel(0, -distance, duration = 0.1)

Run this code, we will see:

Use Mouse to Draw in Python