0

my problem is that pygame cant find my picture (bg.png)

class Background(pygame.sprite.Sprite):
    def __init__(self, image_file, location):
        pygame.sprite.Sprite.__init__(self)  #call Sprite initializer
        self.image = pygame.image.load(image_file)
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = location
BackGround = Background ('bg.PNG', [0, 0] )
ram kador
  • 49
  • 5

1 Answers1

0

The image filepath has to be relative to the current working directory. The working directory is possibly different to the directory of the python file.

The name and path of the file can be get by __file__. The current working directory can be get by os.getcwd() and can be changed by os.chdir(path).

One solution is to change the working directory:

import os

sourceFileDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(sourceFileDir)

An alternative solution is to find the absolute path. If the image is relative to the folder of the python file (or even in the same folder), then you can get the directory of the file and concatenate the image filename. e.g.:

import pygame
import os

# get the directory of this file
sourceFileDir = os.path.dirname(os.path.abspath(__file__))

# [...]

class Background(pygame.sprite.Sprite):
    def __init__(self, image_file, location):
        pygame.sprite.Sprite.__init__(self)  #call Sprite initializer
        
        imgPath = os.path.join(sourceFileDir, image_file)
        self.image = pygame.image.load(imgPath)
        
        # [...]
Rabbid76
  • 202,892
  • 27
  • 131
  • 174