Search code examples
pythonarcade

Loading .png file for use as a sprite in Python Arcade


I am trying to create a Player class in Python Arcade wherein I use a .png image of a rectangle to create a sprite which the user moves in order to hit a ball. However, whenever I run the program, I receive a "FileNotFoundError". The file name is Red_Rectangle.png and it is currently located on my desktop. Below is an excerpt of the code that I am using. The error is triggered in the line containing "Red_Rectangle.png".

def MyGame(arcade.Window):

    def __init__(self, width, height):
        super().__init__(width, height)
        self.player_list = None
        self.player_sprite = None
        self.score = 0

        arcade.set_background_color(arcade.color.BLACK)

    def setup(self):
        self.player_list = arcade.SpriteList()

        self.score = 0
        self.player_sprite = Player("Red_Rectangle.png", SPRITE_SCALING)
        self.player_sprite.center_x = 50
        self.player_sprite.center_y = 50
        self.player_list.append(self.player_sprite)

Solution

  • It is because if you do a os.listdir it will not return that the image is there, when Player method would want 'E:/somedir/Red_Rectangle.png' because the file does not exist in the current directory.

    Use os.path.join to prepend the directory to your filename:

    import os
    path = r'E:/somedir'
    def MyGame(arcade.Window):
    
        def __init__(self, width, height):
            super().__init__(width, height)
            self.player_list = None
            self.player_sprite = None
            self.score =0
            arcade.set_background_color (arcade.color.BLACK)
    
        def setup(self):
            self.player_list = arcade.SpriteList()
            self.score = 0
            self.player_sprite = Player(os.path.join(path, "Red_Rectangle.png"), SPRITE_SCALING)
            self.player_sprite.center_x = 50
            self.player_sprite.center_y = 50
            self.player_list.append (self.player_sprite)
    

    Or simply place the image file in the working directory.