Search code examples
pythonpygame

Why is my pygame not responding when add buttons?


I'm trying to add buttons into my pygame platformer but when I run I either can't click the buttons or the game won't respond depending on if I add pygame.display.update or not.

run = True
start_game = False
while run:
clock.tick(27)
#sets fps to 27

    if start_game == False:
        if start_button.draw(win):
            start_game = True
        if quit_button.draw(win):
            run = False

        pygame.display.update()

    else:

        platform_img.draw(win)

Here is my code for when clicking the buttons and depending on whether I add the pygame.display.update() the buttons either won't work or the program won't respond

class Button():
    def __init__ (self, x, y, image, scale):
        width = image.get_width()
        height = image.get_height()
        self.image = pygame.transform.scale(image, (int(width * scale), int(height * scale)))
        self.rect = self.image.get_rect()
        self.rect.topleft = (x, y)
        self.clicked = False

    def draw(self, surface):
        action = False
        pos = pygame.mouse.get_pos()
        if self.rect.collidepoint(pos):
            if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
                self.clicked = True
        if pygame.mouse.get_pressed()[0] == 0:
            self.clicked = False

        surface.blit(self.image, (self.rect.x, self.rect.y))
        return action

This is my button class


Solution

  • You have to handle the events in the application loop. See pygame.event.get() respectively pygame.event.pump():

    For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.

    For example, add an event loop and the QUIT event:

    while run:
        clock.tick(27)
    
        # handle events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
    
        if start_game == False:
            if start_button.draw(win):
                start_game = True
            if quit_button.draw(win):
                run = False
        else:
            platform_img.draw(win)
    
        pygame.display.update()
    

    Note, the typical PyGame application loop has to: