I've been using the "Python Crash Course" book to learn python. I'm currently on page 233-234 and can't seem to get the program to work. I'm supposed to import an image of a ship but every time that I try to do that using the line self.image = pygame.image.load("images/Ship.bmp")
I get an error saying "FileNotFoundError: No file 'Ship.bmp' found in working directory. Where is my working directory and how do I get my file there? (using visual studious)
class Ship:
def __init__(self, ai_game):
self.screen = ai_game.screen
self.screen_Rect = ai_game.screen.get_rect()
self.image = pygame.image.load("images/Ship.bmp")
self.rect = self.image.get_rect()
self.rect.midbottom = self.screen_rect.midbottom
def blitme(self):
self.screen.blit(self.image, self.rect)
in a different class:
self.ship = Ship(self)
CodePudding user response:
Here's how to determine an absolute path to the image file based on the location of your script file. Doing it this way will make your code work regardless of what the current working directory happens to be.
It uses the Path
class in the pathlib
module to make things very simple (there's no need to use os.path
to do things as I mentioned in my comment — although it could also be done using it).
from pathlib import Path
class Ship:
# Determine absolute path from relative path.
image_path = Path(__file__).parent / "images/Ship.bmp"
def __init__(self, ai_game):
self.screen = ai_game.screen
self.screen_Rect = ai_game.screen.get_rect()
self.image = pygame.image.load(self.image_path)
self.rect = self.image.get_rect()
self.rect.midbottom = self.screen_rect.midbottom
def blitme(self):
self.screen.blit(self.image, self.rect)
print(Ship.image_path) # -> Will show absolute path to image file.
I'm not sure what you meant about the "in a different class:" part (or even what the snippet of code shown below it is supposed to accomplish).