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)
# [...]