Home > Blockchain >  I need to install a picture, but it gives an error
I need to install a picture, but it gives an error

Time:02-14

I am trying to create a game based on Eric Matiz's book "learning python" and created the Ship module, there is an error in this module that I cannot solve

Here is the code itself:

import pygame


class Ship():

    def __init__(self, screen):
        """Init ship and sets its starting position"""
        self.screen = screen

        # load image ship and gets rectangle.
        self.image = pygame.image.load('images/ship.bmp')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        # every new ship is starting in bottom edge screen.
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom

    def bliteme(self):
        """Draws the ship at the current position."""
        self.screen.blit(self.image, self.rect)

I tried to do it through the "os" module, but nothing worked Error:

self.image = pygame.image.loading('images/ship.bmp')
FileNotFoundError error: There is no such file or directory.

The file is located in the "images" directory with the name "ship.bmp", the path is specified correctly, but still gives an error

I tried to find an answer on the internet, but mostly such errors remain without a working answer

CodePudding user response:

It is not enough to put the files in the same directory or sub directory. You also need to set the working directory. The image file path has to be relative to the current working directory. The working directory is possibly different to the directory of the python script.
Put the following at the beginning of your code to set the working directory to the same as the script's directory:

import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
  • Related