Mouse Clicked on Image in Pygame

So, now that our image can animate and wrap around the screen, let’s try to click on it!

First, though we should just take moment to learn about how the mouse itself works in pygame.

Download Code
Download Code

The important new lines which are now part of our game loop is to constantly look to see if the mouse click event is fired (line 21) and then, if so, to see if the x,y coordinates of the mouse are inside the rectangle (line 24)

pygame-mouse-event-example-code

Full Code

import pygame

pygame.init()
width=350;
height=400
screen = pygame.display.set_mode( (width, height ) )
pygame.display.set_caption('clicked on image')
redSquare = pygame.image.load("images/red-square.png").convert()

x = 20; # x coordnate of image
y = 30; # y coordinate of image
screen.blit(redSquare ,  ( x,y)) # paint to screen
pygame.display.flip() # paint screen one time

running = True
while (running):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            # Set the x, y postions of the mouse click
            x, y = event.pos
            if redSquare.get_rect().collidepoint(x, y):
                print('clicked on image')
#loop over, quite pygame
pygame.quit()