Search code examples
pythonpygame

Why does the screen stay the same color after pushing the button?


import pygame

pygame.init()
screen = pygame.display.set_mode((700, 700))
pygame.display.set_caption('Checkers')


while True:
  screen.fill((114,157,224))
  pygame.display.update()
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
    pygame.quit()
  elif event.type == pygame.KEYDOWN:
    if event.key == pygame.K_a:
      screen.fill((70,44,133))
      pygame.display.update()

I tried to change pygame.KEYDOWN to pygame.key.get_pressed() but nothing changed.


Solution

  • You should update the display in every frame, but you have to change the Color used to fill the display when the button is pressed:

    clock = pygame.time.Clock()
    fillColor = pygame.Color(114,157,224)
    
    run = True
    while run:
        clock.tick(100)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_a:
                    fillColor = pygame.Color(70,44,133)
      
        screen.fill(fillColor)
    
        # draw scene
        # [...]
      
        pygame.display.update()
    
    pygame.quit()
    

    The typical PyGame application loop has to: