Draw order overwriting Mousedown event drawn image

Viewed 35

I have the following working program. When clicked the image is drawn at the location but immediately disappears as it is only drawn when mouse down event. I would like the image to remain permanently on the screen after mouse down event is over.

import pygame

BLUE = (0, 0, 255)
BLACK = (255,255,255)

pygame.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()

all_sprites = pygame.sprite.Group()
player_image = pygame.image.load('Player.png').convert()
start_rect = player_image.get_rect()
image_rect = start_rect

running = True
while running:
    # keep running at right fps
    clock.tick(30)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            print("Item created at (%d, %d)" % event.pos)
            screen.blit(player_image, (event.pos[0], event.pos[1]))

    all_sprites.update()
    screen.fill(BLUE)

    all_sprites.draw(screen)

    # nachdem alles gezeichnet ist flip display
    pygame.display.flip()

pygame.quit()

I can place the event block below the screen.fill(BLUE), then the image stays for a few milliseconds but none of the two options display the player image permanently.

Thank you for your help.

1 Answers

You have to store the positions to a variable (player_position). Draw the image in the main application loop when the variable is set:

player_position = None

running = True
while running:
    # keep running at right fps
    clock.tick(30)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            print("Item created at (%d, %d)" % event.pos)
            player_position = event.pos

    all_sprites.update()
    screen.fill(BLUE)

    all_sprites.draw(screen)

    if player_position != None:
        screen.blit(player_image, player_position)

    # nachdem alles gezeichnet ist flip display
    pygame.display.flip()

pygame.quit()
Related