0

I copied this function from one of my older projects, on which it works perfectly, but it doesn't work anymore. The button is supposed to detect when the cursor is above it, and redraw itself in a lighter colour, and then when the cursor moves off, it redraws itself in the usual darker colour. But now when the cursor is above it, it doesn't change. It doesn't respond to clicking either. Here is the code

def button(text, x, y, width, height, inactive_color, active_color, action = None):
    cur = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    if x + width > cur[0] > x and y + height > cur[1] > y:
        pygame.draw.rect(gameDisplay, active_color, (x, y, width, height))
        pygame.display.update()
        if click[0] == 1 and action != None:
            if action == 'correct':
                print('correct!')
    else:
        pygame.draw.rect(gameDisplay, inactive_color, (x, y, width, height))

    text_to_button(text, black, x, y, width, height)
    pygame.display.update()

button('test', 100, 100, 100, 50, darkGreen, green, action = 'correct')
Normy Haddad
  • 181
  • 9
  • Please read the [Minimal, Complete and Verifiable example](https://stackoverflow.com/help/mcve) page and provide a runnable example. You can find some button examples [here](https://stackoverflow.com/questions/47639826/pygame-button-single-click). – skrx Nov 08 '18 at 15:42

1 Answers1

0

You are calling the button function once. It runs through the code of the function and terminates, and does not respond further to any inputs -- because it only ran once (almost instantly).

Perhaps if you called this method every time a mouse movement event occurs in the Pygame evnet queue it may work.

Alternatively, consider using an object instead of a function for this, such as:

class Button():
    def __init__(self, x, y, width, height, text, action):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text
        self.action = action
        self.label = myfont.render(self.text, 1, (0,0,0))


    def render(self, window):
        if self.visible == True:
            pygame.draw.rect(window, (255,255,255), [self.x, self.y, self.width, self.height])
            window.blit(self.label, (self.x, self.y))

    def pressed(self):
            self.action(self.arguments)

    def hover(self):
            #Here you can implement your code that handles when the mouse hovers over the button. This method can be called by checking mouse movement events in your main loop and seeing if they lie within the coordinates, width, and height of the button.