Search code examples
python-3.ximagepygamebackgroundwindow

Why won't my Pygame window background load?


Whenever I run my code, the window opens just fine but the background image will not load. Although the image won't load immediately, if I minimize the window and open it again, the image loads just fine.

This is my code:

import pygame
import os
pygame.init()

WIDTH, HEIGHT = 500, 365

WIN = pygame.display.set_mode((WIDTH, HEIGHT))

BG = pygame.transform.scale(pygame.image.load(os.path.join("GameMap3.png")).convert_alpha(), (WIDTH, HEIGHT))
PLAYER1 = pygame.image.load(os.path.join("PlayerType1.gif"))

fps = 60
main_font = pygame.font.SysFont("comicsans", 50)
player_vel = 5
clock = pygame.time.Clock()


def Main():
    global BG

    while True:

        WIN.blit(BG, (0,0))

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit(0)

Main()


Solution

  • You missed to update the display with either pygame.display.update() or pygame.display.flip()

    def Main():
        global BG
    
        while True:
    
            WIN.blit(BG, (0,0))
    
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    exit(0)
    
            pygame.display.update() # <--- this is missing
     
    Main()
    

    The typical PyGame application loop has to: