Pygame: Couldn't open file. Same directory

2019-07-19 04:49发布

问题:

I loaded 150 .tif images to a glob module and am currently unable to load them. I'm very new to programming so I imagine it's a dumb mistake I'm missing but I cant seem to figure it out.

The is the code:

import pygame, glob

types= ('*.tif')

artfile_names= []

for files in types:
    artfile_names.extend(glob.glob(files))

print(artfile_names)

for artworks in artfile_names:
    pygame.image.load(str(artfile_names))

Thank you for any help!


回答1:

The mistake is that your types variable is just a string (wrapping it in parentheses has no effect), so you iterate over the letters in the string and call artfile_names.extend(glob.glob(files)) for each letter.

The comma makes the tuple (except for the empty tuple):

types = '*.tif',  # This gives you a tuple with the length 1.

types = '*.tif', '*.png'  # This is a tuple with two elements.

In the second part of your code, you need to iterate over the artfile_names, call pygame.image.load(artwork) to load the image from your hard disk and append the resulting surface to a list:

images = []

for artwork in artfile_names:
    images.append(pygame.image.load(artwork).convert())

Call the .convert() method (or .convert_alpha() for images with transparency) to improve the blit performance.