Last modified: Nov 23, 2024 By Alexander Williams

Track Mouse Movement with pynput.mouse_listener.on_move() in Python

The pynput.mouse_listener.on_move() callback function is essential for tracking mouse cursor movements in Python. It provides real-time coordinates as the mouse moves across the screen.

Basic Implementation of Mouse Movement Tracking

Here's a simple example of implementing mouse movement tracking. This code demonstrates how to create a basic mouse listener that monitors cursor position.


from pynput import mouse

def on_move(x, y):
    # Callback function triggered when mouse moves
    print(f'Mouse moved to ({x}, {y})')

# Create and start the listener
with mouse.Listener(on_move=on_move) as listener:
    listener.join()  # Keep the listener running

When you run this code, it will output the coordinates whenever your mouse moves:


Mouse moved to (156, 234)
Mouse moved to (157, 235)
Mouse moved to (158, 236)

Advanced Movement Tracking Features

You can enhance your mouse tracking by combining it with other mouse events. For a complete solution, you might want to start monitoring mouse events systematically.


from pynput import mouse
import time

class MouseTracker:
    def __init__(self):
        self.last_time = time.time()
        
    def on_move(self, x, y):
        current_time = time.time()
        # Calculate movement speed
        time_diff = current_time - self.last_time
        print(f'Position: ({x}, {y}), Time since last move: {time_diff:.2f}s')
        self.last_time = current_time
        
    def start_tracking(self):
        with mouse.Listener(on_move=self.on_move) as listener:
            listener.join()

# Create and start tracker
tracker = MouseTracker()
tracker.start_tracking()

Error Handling and Monitoring

It's important to implement proper error handling and monitoring. You can check the listener's status to ensure it's working correctly.


from pynput import mouse

def on_move(x, y):
    try:
        print(f'Mouse at ({x}, {y})')
        # Add custom processing here
    except Exception as e:
        print(f'Error processing mouse movement: {e}')

# Create listener with error handling
listener = mouse.Listener(on_move=on_move)
listener.start()

# Check if listener is active
if listener.is_alive():
    print('Mouse listener is active')

Best Practices and Performance Considerations

When implementing mouse movement tracking, consider these important practices:

  • Use throttling to prevent excessive processing
  • Implement proper cleanup mechanisms
  • Handle system-specific coordinate systems

For long-running applications, you might need to implement proper stopping mechanisms to prevent resource leaks.

Conclusion

pynput.mouse_listener.on_move() is a powerful tool for mouse tracking in Python. With proper implementation and error handling, it can be used for various automation and monitoring tasks.