when i press a button, two buttons are being pressed, pygame

前端 未结 1 567
予麋鹿
予麋鹿 2021-01-20 12:56

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

相关标签:
1条回答
  • 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.

    0 讨论(0)
提交回复
热议问题