Why is the PyGame animation is flickering

So I run the code and it just starts glitching out. I am new to pygame.

Here is the code:

import pygame

pygame.init()
# Screen (Pixels by Pixels (X and Y (X = right and left Y = up and down)))
screen = pygame.display.set_mode((1000, 1000))
running = True
# Title and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('Icon.png')
pygame.display.set_icon(icon)
# Player Icon/Image
playerimg = pygame.image.load('Player.png')
playerX = 370
playerY = 480

def player(x, y):
    # Blit means Draw
    screen.blit(playerimg, (x, y))


# Game loop (Put all code for pygame in this loop)
while running:
    screen.fill((225, 0, 0))
    pygame.display.update()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # if keystroke is pressed check whether is right or left
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                print("Left arrow is pressed")

            if event.key == pygame.K_RIGHT:
                print("Right key has been pressed")


            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                print("kEYSTROKE RELEASED")

    # RGB (screen.fill) = red green blue

    player(playerX, playerY)
    pygame.display.update()

The image is not the glitching one as I was not able to post a video but it is what my code does

enter image description here


Solution 1:

The problem is caused by multiple calls to pygame.display.update(). An update of the display at the end of the application loop is sufficient. Multiple calls to pygame.display.update() or pygame.display.flip() cause flickering.

Remove all calls to pygame.display.update() from your code, but call it once at the end of the application loop:

while running:
    screen.fill((225, 0, 0))
    # pygame.display.update() <---- DELETE

    # [...]

    player(playerX, playerY)
    pygame.display.update()

If you update the display after screen.fill(), the display will be shown filled with the background color for a short moment. Then the player is drawn (blit) and the display is shown with the player on top of the background.