0
class Button:

    buttons = []

    def __init__(self, blitX, blitY, textureFile, width, height, rotateAngle=0, hoveredTextureImage=None):
        self.textureImage = pygame.transform.rotate(pygame.transform.scale(pygame.image.load(textureFile), (width, height)), rotateAngle)
        if hoveredTextureImage is not None:
            self.hoveredTextureImage = pygame.transform.rotate(pygame.transform.scale(pygame.image.load(
                                       hoveredTextureImage), (width, height)), rotateAngle)
        else:
            self.hoveredTextureImage = self.textureImage
        self.blitX = blitX
        self.blitY = blitY
        self.height = height
        self.displayImage = self.textureImage

        self.addButton(self)

        self.createMouseParameters()

    def createMouseParameters(self):
        self.startX = self.blitX
        self.endX = self.startX + self.displayImage.get_width()

        self.startY = self.blitY
        self.endY = self.startY + self.displayImage.get_height()

    def draw(self, window):
        window.blit(self.displayImage, (self.blitX, self.blitY))

    def mouseOnButton(self, mouseX, mouseY):
        if self.startX <= mouseX <= self.endX:
            if self.startY <= mouseY <= self.endY:
                self.displayImage = self.hoveredTextureImage
                return True
            else:
                self.displayImage = self.textureImage
        else:
            self.displayImage = self.textureImage

    @classmethod
    def addButton(cls, button):
        cls.buttons.append(button)

    @classmethod
    def detectMouseHover(cls, mouseX, mouseY):
        for button in cls.buttons:
            button.mouseOnButton(mouseX, mouseY)

This is my class for a button. The button is supposed to switch to another image (hoveredTextureImage) when the mouse is on the button. I'm calling the class method "detectMouseHover" in my game loop so that the game can update the button's image. The issue I'm having is that the image is not changing. Any ideas on how to fix it?

I would also appreciate it if anyone has any ideas on how to make the code more concise and simple.

ult
  • 31
  • 3
  • 1
    The `Button` class class seems fine. The bug is elsewhere in your code. – Rabbid76 Apr 29 '21 at 12:58
  • Are you sure you are calling `draw` every frame as well? It's possible you only called it at the start so the image is never being updated. Also make sure you are calling `pygame.display.flip()` every frame. – Luke B Apr 29 '21 at 14:23
  • I draw every button and I use pygame.display.update() and I call the class method detectMouseHover() in the game loop every time. Is there something I'm missing, or is update and flip different? – ult Apr 30 '21 at 12:42

0 Answers0