[Python] Full Control of Mouse Movement and Dragging with PyAutoGUI

目次

Overview

This guide explains how to use PyAutoGUI to move the mouse cursor to a specific location or perform drag-and-drop actions. We will cover how to use the duration parameter to make movements look natural and how to choose between absolute and relative locations.

Specifications

  • Input:
    • Target X and Y coordinates (integers).
    • Movement distance from the current location (integers).
    • Time taken for movement (seconds).
  • Output:
    • Physical movement of the mouse cursor.
    • Dragging actions with the left mouse button held down.
  • Prerequisite: The pyautogui library must be installed.

Basic Usage

This basic code moves the mouse to a specific location over 2 seconds.

import pyautogui

# Enable safety feature (Important)
# Moving the mouse to the top-left corner will force the program to stop.
pyautogui.FAILSAFE = True

# Move slowly to the top-left area (200, 200) over 2.0 seconds.
pyautogui.moveTo(200, 200, duration=2.0)

Full Code Example

This demo code sets an initial position using “absolute movement” and then draws a square using “relative movement.”

import pyautogui
import time

def demo_mouse_movements():
    """
    Runs a demo combining absolute and relative mouse movements.
    """
    # Enable fail-safe feature
    pyautogui.FAILSAFE = True

    print("Starting in 3 seconds. Move mouse to the top-left to stop.")
    time.sleep(3)

    try:
        # 1. Absolute Movement (moveTo)
        # Move to a position near the center
        start_x, start_y = 500, 300
        print(f"Moving to initial position: ({start_x}, {start_y})")
        pyautogui.moveTo(start_x, start_y, duration=1.0)

        # 2. Relative Movement (moveRel) to draw a square
        # Move based on the current position
        distance = 200
        speed = 1.0

        print("Moving right...")
        pyautogui.moveRel(distance, 0, duration=speed)
        
        print("Moving down...")
        pyautogui.moveRel(0, distance, duration=speed)
        
        print("Moving left...")
        pyautogui.moveRel(-distance, 0, duration=speed)
        
        print("Moving up...")
        pyautogui.moveRel(0, -distance, duration=speed)

        print("Done.")

    except pyautogui.FailSafeException:
        print("\nFail-safe triggered. Emergency stop.")

if __name__ == "__main__":
    demo_mouse_movements()

Customization Points

Differences Between Movement and Dragging Functions

PyAutoGUI offers two types of actions: “movement” and “dragging” (moving while clicking). Each type can use “absolute” or “relative” coordinates.

Function NameAction TypeDescription
pyautogui.moveTo(x, y)Movement (Absolute)Moves to coordinates where (0,0) is the top-left.
pyautogui.moveRel(x, y)Movement (Relative)Moves by a specific distance from the current position.
pyautogui.dragTo(x, y)Dragging (Absolute)Moves to coordinates while holding the mouse button.
pyautogui.dragRel(x, y)Dragging (Relative)Drags by a specific distance from the current position.

Meaning of the duration Parameter

All movement and dragging functions accept a duration argument.

  • duration=0.0 (default): The cursor moves instantly. This speed is impossible for humans and might be detected by bot security.
  • duration=value (e.g., 0.5, 2.0): The cursor moves to the target over the specified seconds. This makes the movement smooth and easy to follow visually.

Important Notes

  • Fail-Safe Feature (FAILSAFE): If an automated script goes out of control, you might lose mouse control. Setting pyautogui.FAILSAFE = True allows you to force stop the script by pushing the mouse into a corner (usually top-left). Always enable this.
  • Screen Resolution and Out-of-Range Errors: Using coordinates outside the screen size may cause errors. Keep your targets within the range returned by pyautogui.size().
  • Interference with Other Apps: If an unintended window is in the front, the script might click or drag on that window. It is safer to confirm the active window before running.

Application

This example shows a dragging operation, similar to drawing a line in paint software. Using dragRel allows you to draw shapes regardless of where you start.

import pyautogui
import time

def draw_triangle_shape():
    """
    Performs a drag operation to draw a triangle from the current position.
    """
    pyautogui.FAILSAFE = True
    
    print("Please select your canvas within 5 seconds...")
    time.sleep(5)
    
    print("Starting drawing...")
    
    length = 150
    draw_speed = 0.5
    
    # Drag down-right
    pyautogui.dragRel(length, length, duration=draw_speed, button='left')
    
    # Drag left
    pyautogui.dragRel(-length * 2, 0, duration=draw_speed, button='left')
    
    # Drag back to the start (up-right)
    pyautogui.dragRel(length, -length, duration=draw_speed, button='left')
    
    print("Drawing finished.")

if __name__ == "__main__":
    draw_triangle_shape()
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次