How to move an image with the mouse in PyGame?

How to move an image with the mouse in PyGame?

Moving an image with the mouse in Pygame involves capturing the mouse position and events, then updating the image's position based on the mouse's current position. Below is a simple example illustrating how you can make an image follow the mouse cursor in Pygame.

First, make sure you have Pygame installed:

pip install pygame 

Then, you can use the following script as a starting point:

import pygame import sys # Initialize Pygame pygame.init() # Set up the display width, height = 640, 480 screen = pygame.display.set_mode((width, height)) pygame.display.set_caption('Move Image with Mouse') # Load the image image = pygame.image.load('path_to_your_image.png') # Replace with your image path image_rect = image.get_rect() # Set up the clock to control frames per second clock = pygame.time.Clock() # The main game loop running = True while running: # Limit frame rate to 60 frames per second clock.tick(60) # Event handling for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Get the current position of the mouse mouse_x, mouse_y = pygame.mouse.get_pos() # Update the image rect's center to the mouse position image_rect.center = (mouse_x, mouse_y) # Drawing screen.fill((255, 255, 255)) # Fill the screen with white to clear it screen.blit(image, image_rect) # Draw the image at its new position # Update the display pygame.display.flip() # Quit Pygame pygame.quit() sys.exit() 

In this script:

  • We load an image and get its rectangle (rect) which Pygame uses to position the image.
  • In the game loop, we handle events and check if the user has requested to close the window.
  • We get the current mouse position with pygame.mouse.get_pos().
  • We set the center of the image's rect to the current mouse position, so the image will be centered on the cursor.
  • We fill the screen with white color to clear the old frames.
  • We draw the image at its updated position.
  • We update the display with pygame.display.flip().

Make sure to replace 'path_to_your_image.png' with the actual path to your image file.

This script will make the image follow the mouse cursor in real-time. You can run this script and move your mouse across the Pygame window to see the effect.


More Tags

prompt istio-gateway tflearn sonarqube-scan fullscreen erp angular-fullstack text-cursor create-guten-block excel-formula

More Programming Guides

Other Guides

More Programming Examples