Search code examples
pythonpygamemouseclick-event

Pygame: getting a loop to run after mouse click


I want to get a certain loop to run after the mouse has previously been clicked. I initiated a variable called mouse_clicked to false, and then change it to True after the mouse has been clicked. However, this doesn't seem to get things going afterwards. Here's my code:

import sys, pygame

size = width, height = 320, 240
screen = pygame.display.set_mode(size)

running = True
mouse_pressed = False

while running:
    while mouse_pressed:
        rect = pygame.Rect(10, 20, 30, 30)
        pygame.draw.rect(screen, (255,0,0), rect)
        pygame.display.flip()

        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pressed = True
            if event.type == pygame.QUIT:
                running = False    
sys.exit(0)

Thanks! omer


Solution

  • EDITED after answering too quickly

    move your loop around:

    while running:
        rect = pygame.Rect(10, 20, 30, 30)
        pygame.draw.rect(screen, (255,0,0), rect)
        pygame.display.flip()
    
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pressed = True
            if event.type == pygame.QUIT:
                running = False   
    
        while mouse_pressed:
            # do your stuff
            mouse_pressed = False
    

    In your version, the whole loop never starts, since mouse_pressed is initialized to False.