I am trying to make a rectangle pop up when middle click is pressed, and stay popped up until I press left click in pygame.
Here is my code:
button1, button2, button3 = pygame.mouse.get_pressed()
if button2 == True:
pygame.draw.rect(screen, ((255, 0, 0)), (0, int(h/2), int(w/6), int(h/2)-40), 0)
pygame.display.update()
The thing is, when I press middle click, the rectangle appears, then disappears instantly.
I have tried putting it as while button2 == 2:
, but the program hangs.
Thank you!!
Since you want to react to different mousebutton clicks, it's better to listen for the
MOUSEBUTTONUP
(orMOUSEBUTTONDOWN
) events instead of usingpygame.mouse.get_pressed()
.You want to change the state of your application when a mousebutton is pressed, so you have to keep track of that state. In this case, a single variable will do.
Here's a minimal complete example:
Change
to
then have
somewhere in your main loop (before
pygame.display.update
).Another thing is that you do not need to say
if some_variable == True:
. Instead you can just sayif some_variable:
. They do the exact same thing.