1

I was trying to load a png file to python by pygame and it doesn't work this is my code:

import pygame
from pygame.locals import *
pygame.init()
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Game")
clock = pygame.time.Clock()
carImage = pygame.image.load('you.png')
def car(x,y):
    gameDisplay.blit(carImage,(x,y))
    x = (display_width * 0.45)
    y = (display_height * 0.8)
    crashed = False
    while not crashed:
       for event in pygame.event.get():
           if event.type == pygame.QUIT:
               crashed = True
       gameDisplay.fill(white)
       car(x,y)
       pygame.display.update()
       clock.tick(24)
    pygame.quit()
    quit()

and it says:

Traceback (most recent call last):

File "C:/Users/Dawn/PycharmProjects/snakegame/snake.py", line 13, in carImage = pygame.image.load('you.png')

pygame.error: Couldn't open you.png

Please help me I don't know why this keep showing.

I'm using window 10 now and I did the C: \.\...\you.png method but it still doesn't work.

Aqueous Carlos
  • 445
  • 7
  • 20

1 Answers1

1

Based on this answer, it's recommended to use relative paths instead. It's always better to do so, since you don't have to care about '\', '/' or OS (someone already did it for us :v).

The problem seems to be it, because the code below works well for me. It's been considered you have an images_store folder to store your images at same father directory as your .py file (of course, you can change it any way you want).

import pygame
import os.path as osp
from pygame.locals import *


pygame.init()

display_width, display_height = 800, 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)

current_path = osp.dirname(__file__)                          # Where your .py file is located
image_path = osp.join(current_path, 'images_store')           # The image folder path
carImage = pygame.image.load(osp.join(image_path, 'you.png'))


gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("Game")
clock = pygame.time.Clock()

def car(x,y):
   gameDisplay.blit(carImage, (x, y))

x = (display_width * 0.45)
y = (display_height * 0.8)
crashed = False
while not crashed:
   for event in pygame.event.get():
       if event.type == pygame.QUIT:
           crashed = True
   gameDisplay.fill(white)
   car(x,y)
   pygame.display.update()
   clock.tick(24)
pygame.quit()
quit()

p.s.1 - See more information about os.path here.

p.s.2 - I'm using MacOS.

roncha
  • 11
  • 2