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.