When I press a button, two buttons are being pressed. I made images to act like a button but when I press the first button, the second button is pressed too. I\'m new to pyg
If you call get_rect
on a Surface
, the resulting Rect
that is returned will always have an x
and y
value of 0
.
So when you run if img.get_rect().collidepoint(mouse_pos)
in your event loop, you're NOT checking if the Surface
was a clicked. You check if the mouse position is in the top left corner of the screen.
Maybe use some print
statements to check for yourself.
What you can do is to create a Rect
for each button outside of your main loop, and then use these rects for blitting:
...
img = pygame.image.load('3.gif')
img_rect = img.get_rect()
...
mg = pygame.image.load('4.gif').convert()
mg_rect = img.get_rect(topleft=(150,0))
...
while True:
...
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = event.pos
if img_rect().collidepoint(mouse_pos):
BEEP1.play()
if mg_rect ().collidepoint(mouse_pos):
BEEP2.play()
screen.blit(img, img_rect)
screen.blit(mg, mg_rect)
Note that you also should avoid time.sleep
or multiple calls of pygame.display.flip()
in your main loop.
Another solution is to use the pygame's Sprite
class, which allows you to combine a Surface
and a Rect
.