Reputation: 882
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!!
Upvotes: 1
Views: 216
Reputation: 101072
Since you want to react to different mousebutton clicks, it's better to listen for the MOUSEBUTTONUP
(or MOUSEBUTTONDOWN
) events instead of using pygame.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:
import pygame, sys
pygame.init()
screen = pygame.display.set_mode((300, 300))
draw_rect = False
rect = pygame.rect.Rect((100, 100, 50, 50))
while True:
for e in pygame.event.get():
if e.type == pygame.QUIT:
sys.exit()
if e.type == pygame.MOUSEBUTTONUP:
if e.button == 2:
draw_rect = True
elif e.button == 1:
draw_rect = False
screen.fill((255, 255, 255))
if draw_rect:
pygame.draw.rect(screen, (0, 0, 0), rect, 2)
pygame.display.flip()
Upvotes: 1
Reputation: 2121
Change
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()
to
button1, button2, button3 = pygame.mouse.get_pressed()
if button2 == True:
rect_blit=True
pygame.display.update()
then have
if rect_blit==True:
pygame.draw.rect(screen, ((255, 0, 0)), (0, int(h/2), int(w/6), int(h/2)-40), 0)
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 say if some_variable:
. They do the exact same thing.
Upvotes: 0