Skip to content
Advertisement

How do I change the image of a button when it’s clicked in pygame?

I have a button class and I can’t figure out how to change the image to a different one to make the button look like it’s been clicked.

I’ve tried changing the button image to a different image from the file after “action” is true, which happens once the button is clicked.

#Load Button Images
SpawnButtonImg = pygame.image.load("imagesSpawnButton.png")
SpawnButtonPressedImg = pygame.image.load("imagesSpawnButtonPressed.png")
#button class
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, screen):
        action = False
        #get mouse position
        pos = pygame.mouse.get_pos()

        #check mouseover and clicked conditions
        if self.rect.collidepoint(pos):
            if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
                self.clicked = True
                action = True

        if pygame.mouse.get_pressed()[0] == 0:
            self.clicked = False

        #draw button on screen
        screen.blit(self.image, (self.rect.x, self.rect.y))
        return action


SpawnButton = Button(1760, 1000, SpawnButtonImg, 1)

def ButtonPress():
    if SpawnButton.draw(screen):
        print('SPAWN')

Advertisement

Answer

You need to load 2 images and set the image that will be displayed depending on the state of self.clicked:

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

    def draw(self, screen):
        action = False
        #get mouse position
        pos = pygame.mouse.get_pos()

        #check mouseover and clicked conditions
        if self.rect.collidepoint(pos):
            if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
                self.clicked = True
                action = True
                self.image = self.imageClicked 

        if pygame.mouse.get_pressed()[0] == 0:
            self.clicked = False
            self.image = self.imageDefault

        #draw button on screen
        screen.blit(self.image, (self.rect.x, self.rect.y))
        return action
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement