0
def box_button(x,y, colour, action=None):
    toggle = False
    pos = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    if click[0] == 1 and (x + 10) + 30 > pos[0] > (x + 10) and (y + 10) + 30 > pos[1] > (y + 10):
        if toggle == True:
            toggle = False
            colour = red
        else:
            toggle = True
            colour = green
    pygame.draw.rect(window, white, (x, y, 50, 50))
    pygame.draw.rect(window, colour, (x + 10, y+10, 30, 30))
    return colour

anyone help this code so it can help me toggle the button from red to green? everytime i click the button with this code all it does it just when i left click, it turns green but when i let go of the click, it goes back to red and i want it to permanentley stay green? thanks

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • `if toggle == True:` —> `if Toggle:`. How do you think if statements work? – AMC Jan 12 '20 at 20:28
  • You should post a [MCVE](https://stackoverflow.com/help/minimal-reproducible-example). The function alone is not enough to understand where the error is, since we do not know when is called. – Valentino Jan 12 '20 at 20:49
  • `click[0] == 1` is `True`, as long the button is holed down. You have to implement the `MOUSEBUTTONDOWN` event. – Rabbid76 Jan 12 '20 at 20:49

1 Answers1

0

click[0] == 1 is True, as long the button is hold down. You have to implement the MOUSEBUTTONDOWN event.

Get the list of events in the main application loop:

events = pygame.event.get()
for event in events:
    if event.type == pygame.QUIT:
        # [...]

Add an events argument to box_button and pass the list of events to the function:

box_button(events, .....)

Check for the MOUSEBUTTONDOWN event in box_button and use pygame.Rect respectively collidepoint for the collision test:

def box_button(events, x, y, colour, action=None):
    toggle = False

    for event in events:
        if event.type == pygame.MOUSEBUTTONDOWN:
            button_rect = pygame.Rect(x + 10, y+10, 30, 30)
            if event.button == 1 and button_rect.collidepoint(event.pos):
                toggle = not toggle
                colour = green if toggle else red

    pygame.draw.rect(window, white, (x, y, 50, 50))
    pygame.draw.rect(window, colour, (x + 10, y+10, 30, 30))
    return colour
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • what would i put in the "events" argument when calling the function?, like eg. box = box_button(events?, 550, 550, white, "no"), what would i put for the events argument? sorry, i am very new to pygame – nico tividad Jan 14 '20 at 09:22
  • @nicotividad Please read the answer. You have to have an event loop somewhere (something like the 1st code snippet in the answer). `events` has to be passed to `box_button` – Rabbid76 Jan 14 '20 at 09:29