Skip to content Skip to sidebar Skip to footer

How To Load Multiple Images In Pygame?

I need to load around 200 images in pygame to be blitted at various points in my game. I tried writing a function for this but kept coming back with NameError: name 'tomato' is not

Solution 1:

You do load the image by calling load("tomato"), but you ignore the return value. Try

tomato = load("tomato")

instead.

Solution 2:

If you want to load so many images, use os.listdir and put all the images in the directory into a dictionary. Also, use convert or convert_alpha after loading the images to improve the performance.

defload_images(path_to_directory):
    """Load images and return them as a dict."""
    image_dict = {}
    for filename in os.listdir(path_to_directory):
        if filename.endswith('.png'):
            path = os.path.join(path_to_directory, filename)
            key = filename[:-4]
            image_dict[key] = pygame.image.load(path).convert()
    return image_dict

If you want to load all images from subdirectories as well, use os.walk:

defload_images(path_to_directory):
    """Load all images from subdirectories and return them as a dict."""
    images = {}
    for dirpath, dirnames, filenames in os.walk(path_to_directory):
        for name in filenames:
            if name.endswith('.png'):
                key = name[:-4]
                img = pygame.image.load(os.path.join(dirpath, name)).convert()
                images[key] = img
    return images

Post a Comment for "How To Load Multiple Images In Pygame?"