简体   繁体   中英

How do i load images that are not in the working directory?

Im trying to program chess in python using pygame but i cant load images from a diferent directory, here's the code.

king=pygame.image.load(os.path.basename(r"C:\Users\tiago\PycharmProjects\chess\pieces\w_king.png"))
pos = [4, 0]
coords = translate_coord(pos)
display.blit(king, coords)
pygame.display.flip()

i keep getting the "FileNotFoundError: No such file or directory." error and i don know whats wrong.

You can just pass the file path string to pygame.image.load without using os.path.basename . Also, you can pass a relative path instead, and if you want to make the file path cross platform, you can call os.path.join() like this, assuming the current working directory is C:\\Users\\tiago\\PycharmProjects\\chess :

king = pygame.image.load(os.path.join("pieces", "w_king.png"))

The issue with what you have is that os.path.basename is returning w_king.png , but assuming your current working directory is C:\\Users\\tiago\\PycharmProjects\\chess , pygame cannot find the file because what it actually needs to find is pieces\\w_king.png , hence why in my solution above I have os.path.join("pieces", "w_king.png")) , which would return pieces\\w_king.png on your system.

Edit:

As mentioned by @Rabbid76 you should make sure that the current working directory is the same directory as the source file before the code to load the image, if you are passing a relative path, like so:

os.chdir(os.path.dirname(os.path.abspath(__file__)))
king = pygame.image.load(os.path.join("pieces", "w_king.png"))

Dont use os.path.basename This returns w_king.png in your case.

It looks like pygame.image.load requires a file type object. You can obtain this using open()

with open(r"C:\Users\tiago\PycharmProjects\chess\pieces\w_king.png") as filehandle:
    king=pygame.image.load(filehandle)

# do stuff with king
pos = [4, 0]
coords = translate_coord(pos)
display.blit(king, coords)
pygame.display.flip()

Edit: Nevermind, looks like pygame.image.load can also handle a file path string although I believe my answer also works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM