How do I detect if the mouse is hovering over a button? PyGame button class is not displaying the text or changing colour on hover

The condition

if self.x < x < self.width and self.y < y < self.height:

is wrong. You have to evaluate if x < self.x + self.width and y < self.y + self.height:

if self.x < x < self.x + self.width and self.y < y < self.y + self.height:
    # [...]

Anyway, I recommend to pygame.Rect / collidepoint() for the collision test:

button_rect = pygame.Rect(self.x, self.y, self.width, self.height)
if button_rect.collidepoint((x, y):
    # [...]

button_rect can be used further for drawing the rectangle:

pygame.draw.rect(screen, (211, 211, 211), button_rect)

The code can be simplified a lot by the use of an attribute rect rather than the separate attributes x, y, width, height:

class Button:
    def __init__(self, color, x, y, width, height, text, fontsize):
        self.color = color
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.fontsize = fontsize
        self.courier_button_font = pygame.font.SysFont("Courier", self.fontsize)

    def draw(self, pos):

        button_color = (211, 211, 211) if self.rect.collidepoint(pos) else self.color
        pygame.draw.rect(screen, button_color, self.rect)

        text_width, text_height = self.courier_button_font.size(self.text)
        textpos = (self.rect.centerx - text_width // 2, self.rect.centery - text_height // 2)
        buttontext = Fonts(courier_font, True, self.text, BLACK, textpos)
        buttontext.draw(screen)

    def isOver(self, pos):
        return self.rect.collidepoint(pos)

Leave a Comment