1

I am trying to use the pygame.image.load() function to create an image while following a tutorial.

This is the code that I used:

import pygame
pygame.init()
running=True
screen = pygame.display.set_mode((1350, 700))
pygame.display.update()
wheel = pygame.image.load('wheel_image.png')
while running:
    screen.fill(0, 0, 0)
    for event in pygame.event.get():
        if event.type ==pygame.QUIT:
            running=False
    screen.blit(wheel, (675, 350))
    pygame.display.update()

But when I run it, it gives this error message:

line 6, in <module>
    wheel = pygame.image.load('wheel_image.png')
pygame.error: Couldn't open wheel_image.png

I have the png file in the same directory as my code, so have I made an error in my code or what could be causing this?

1 Answers1

0

Whether the file can be found depends on the location from where you call your code. That's inconvenient so better calculate the project's base path using the __file__ property:

from pathlib import Path

BASE = Path(__file__).resolve().parent
wheel_path = BASE / 'wheel_image.png'
wheel = pygame.image.load(wheel_path)

If you use an older version of pygame that can't handle Path objects, manually turn it into a string:

wheel_path = str(BASE / 'wheel_image.png')
Jan Wilamowski
  • 3,308
  • 2
  • 10
  • 23