In this Pygame article we want to learn How to Track Mouse Movement in Pygame, in Pygame tracking mouse movement is an important feature for many games and applications. in this article we want to talk about this concept in Pygame.
This is the complete code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import pygame pygame.init() # Create display surface screen = pygame.display.set_mode((800, 600)) # Load object image object_image = pygame.image.load('icon.png') object_rect = object_image.get_rect() # Main loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == pygame.MOUSEMOTION: mouse_pos = event.pos # Move object based on mouse position object_rect.x = mouse_pos[0] object_rect.y = mouse_pos[1] # Blit object to the display screen.blit(object_image, object_rect) # Update the display pygame.display.update() |
First we need to import Pygame and initialize it. this will allow us to create a display surface and listen for mouse events.
1 2 |
import pygame pygame.init() |
After that we need to create a display surface on which is used for tracking mouse movement. Pygame provides display module that we can use to create display surface.
1 |
screen = pygame.display.set_mode((800, 600)) |
Pygame provides an event system that allows us to listen for mouse events. we can use this system to track mouse movement.
1 2 3 |
while True: for event in pygame.event.get(): if event.type == pygame.QUIT: |
Now that we have tracked the mouse position, we can use it to do something in our game or application. for example, we want that the mouse position to move a player character or to detect if the mouse cursor is over a particular object.
1 2 3 4 5 6 7 8 9 |
while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == pygame.MOUSEMOTION: mouse_pos = event.pos object_rect.x = mouse_pos[0] object_rect.y = mouse_pos[1] |
Run your code and this will be the output

So in this blog post, we have explored tracking mouse movement in Pygame. We learned how to import and initialize Pygame, create a display surface, handle mouse movement events and use the mouse position to do something in our game or application.
Learn More on Pygame
- Pygame Display: Setting Up Game Window
- Pygame Init: Getting Started with Pygame
- Pygame Caption: Giving Your Game a Title
- How to Draw Rectangles on Pygame
- How to Control Pygame Frame Rate
- How to Handle User Input in Pygame
- How to Detect Key Presses in Pygame
- How to Work with Fonts in Pygame
- How to Display Image in Pygame