2

Trying to make a menu screen with multiple clickable images using pygame

based around this

https://blog.penjee.com/mouse-clicked-on-image-in-pygame/

however when i insert more than one image it prints both statements instead of one statement depending on which image is clicked

import pygame

pygame.init()
width=350;
height=400
screen = pygame.display.set_mode( (width, height ) )
pygame.display.set_caption('clicked on image')
buttonone = pygame.image.load("buttonone.png").convert()
buttontwo = pygame.image.load("buttontwo.png").convert()

screen.blit(buttonone ,  ( 30,40)) # paint to screen
screen.blit(buttontwo ,  ( 120,150)) # 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 buttonone.get_rect().collidepoint(x,y):
                print('clicked on image')
        if event.type == pygame.MOUSEBUTTONDOWN:
            # Set the x, y postions of the mouse click
            x, y = event.pos
            if buttontwo.get_rect().collidepoint(x,y):
                print('clicked on image2')
pygame.quit()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Philly500
  • 41
  • 4

1 Answers1

2

pygame.Surface.get_rect.get_rect() returns a rectangle with the size of the Surface, but the origin of the rectangle is at (0, 0), because the Surface object has no location. The Surface is placed at a position when it is blit to the display.

You've to set the .topleft position, which is used to blit the Surface, to the pygame.Rect objects:

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

            buttonone_rect = buttonone.get_rect(topleft = (30, 40))
            if buttonone_rect.collidepoint(x,y):
                print('clicked on image')

            buttontwo_rect = buttonone.get_rect(topleft = (120, 150))
            if buttontwo_rect.collidepoint(x,y):
                print('clicked on image2')
Rabbid76
  • 202,892
  • 27
  • 131
  • 174