IndexError
builtins.IndexError
Stack trace
Traceback (most recent call last):
File "app.py", line 42, in <module>
pyautogui.click(x=1500, y=1200) # Coordinates outside screen bounds
File "/usr/local/lib/python3.9/site-packages/pyautogui/__init__.py", line 1234, in click
raise IndexError('Mouse click coordinates out of bounds')
IndexError: Mouse click coordinates out of bounds Why it happens
Mouse click functions require coordinates within the screen or window limits. If the coordinates exceed these bounds, the underlying GUI automation library raises an IndexError to prevent invalid operations.
Detection
Check mouse click coordinates against screen resolution or window size before calling click functions. Log or assert coordinate validity to catch out-of-bounds errors early.
Causes & fixes
Coordinates passed to the mouse click function exceed the screen resolution.
Retrieve the screen size dynamically using libraries like pyautogui.size() and clamp click coordinates within these bounds.
Hardcoded coordinates do not account for different screen sizes or multi-monitor setups.
Avoid hardcoding coordinates; instead, calculate positions relative to the active window or screen size at runtime.
Window or UI element moved or resized, making previous click coordinates invalid.
Query the current window position and size before clicking, and adjust coordinates accordingly.
Code: broken vs fixed
import pyautogui
# This will raise IndexError if coordinates are out of screen bounds
pyautogui.click(x=1500, y=1200) # Coordinates may be invalid import pyautogui
# Get screen size dynamically
screenWidth, screenHeight = pyautogui.size()
# Clamp coordinates within screen bounds
x = min(1500, screenWidth - 1)
y = min(1200, screenHeight - 1)
pyautogui.click(x=x, y=y) # Fixed: coordinates guaranteed in bounds
print(f"Clicked at ({x}, {y})") Workaround
Wrap mouse click calls in try/except IndexError, and on exception, log the invalid coordinates and skip or adjust the click to a safe default position.
Prevention
Always dynamically query screen or window dimensions before mouse interactions and calculate click positions relative to current UI layout to avoid hardcoded out-of-bounds coordinates.