Search code examples
pythonclassbackgroundpygame

Pygame can't get background image to load?


All I get is a black screen. Not sure if I can't find the image in the directory or, if some if I'm not calling something right... But it's not giving me an error so I'm not sure what to work off of.

import pygame
# Intialize the pygame
pygame.init()

# Create the screen 
screen = pygame.display.set_mode((300, 180))

#Title and Icon
pygame.display.set_caption("Fighting Game")

# Add's logo to the window 
# icon = pygame.image.load('')
# pygame.display.set_icon(icon)

#  Game Loop
running = True
while running:
    # screen.fill((0, 0, 0))
    # screen.blit(BackGround.image, BackGround.rect)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False


class Background(pygame.sprite.Sprite):
    def __init__(self, image_file, location):
        pygame.sprite.Sprite.__init__(self)  #call Sprite initializer
        self.image = pygame.image.load("images/image.png")
        self.rect = self.image.get_rect(300,180)
        self.rect.left, self.rect.top = location

BackGround = Background('image.png', [0,0])

screen.fill((0, 0, 0))
screen.blit(BackGround.image, BackGround.rect)

Solution

  • You have to blit the image in the main application loop and you have to update the display by pygame.display.flip.

    Furthermore it is not necessary to pass any parameters to self.image.get_rect(). Anyway the arguments to get_rect() have to be keyword arguments. What you can do is to set the location by the keyword argument topleft.

    class Background(pygame.sprite.Sprite):
        def __init__(self, image_file, location):
            pygame.sprite.Sprite.__init__(self)  #call Sprite initializer
            self.image = pygame.image.load("images/image.png")
            self.rect = self.image.get_rect(topleft = location)
    
    BackGround = Background('image.png', [0,0])
    
    #  Game Loop
    running = True
    while running:
        # screen.fill((0, 0, 0))
        # screen.blit(BackGround.image, BackGround.rect)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
    
        #screen.fill((0, 0, 0)) # unnecessary because of the background image
        screen.blit(BackGround.image, BackGround.rect)
        pygame.display.flip()
    

    Note, the main application loop has to:

    • handle the events
    • clear the display or blit the backgrond image
    • draw the scene
    • update the display