0

I was following a starter tutorial on Pygame but at some point of the video, we can see he has "ufo.png" as a Pycharm file on the left side of the screen and as a tab. Video link at the right timecode: https://youtu.be/FfWpgLFMI7w?t=762

He explains how to download the file from flaticon.com (32px) but not how to get it into Pycharm. I tried to to just slide into the tab bar to create a new tab with the file in it, and it works, but the script cannot find it. It might be because although the file is a new tab, it doesn't appear in the folder on the right side, unlike "main.py" or "ufo.png" in the video.

Anyway, this is my script so far.

import pygame

# Initialize the pygame
pygame.init()

#create the screen
screen = pygame.display.set_mode((800, 600))

#Title and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('ufo (1).png')
pygame.display.set_icon(icon)

#Game Loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    #RGB - Red, Green, Blue
    screen.fill((67, 44, 123))

And this is the error message I get

Traceback (most recent call last):  
  File "D:\Users\xxxxx\PycharmProjects\SpaceInvader\main.py", line 11, in <module>
    icon = pygame.image.load('ufo (1).png')
FileNotFoundError: No such file or directory.

Process finished with exit code 1

Edit: I don't understand anything about these os things, how is my question a duplicate of Could not open resource file: pygame.error: Couldn't open sprite/test_bg.jpg ? Please let me just ask my question, I don't have a sufficient Python level to understand the link between those two questions. Please.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Codem
  • 1
  • *"Please let me just ask my question, I don't have a sufficient Python level to understand the link between those two questions. Please."* - The behavior is well explained in the duplicate question. You just have to read it. The answer to this question is just to copy/paste the answer to the duplicate question. – Rabbid76 May 01 '21 at 13:23

1 Answers1

0

The resource (image, font, sound, etc.) file path has to be relative to the current working directory. The working directory is possibly different to the directory of the python file.

The name and path of the file can be get by __file__. The current working directory can be get by os.getcwd() and can be changed by os.chdir(path).

If the file is in an subfolder of the python file (or even in the same folder), then you can get the directory of the file and join (os.path.join()) the relative filepath. e.g.:

import pygame
import os

# get the directory of this file
sourceFileDir = os.path.dirname(os.path.abspath(__file__))

# [...]

# join the filepath and the filename
filePath = os.path.join(sourceFileDir, 'YOUR FILE DIRECTORY/ufo (1).jpg')

icon = pygame.image.load(filePath)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174