Search code examples
pythonpython-3.xfilepygamenameerror

Why is this nameError occurring


I am 9 and self teaching, please be kind and keep that in mind when you reply, thank you very much for your time.

I have the image Bluecar.png and the following code in the same file:

import pygame, time
pygame.init()
(width, height) = (300, 200)
screen = pygame.display.setmode((width, height))
pygame.display.flip()

player = Bluecar.png
screen.blit(player)
while True:
    time.sleep(0.1)

But, it causes this error:

Traceback (most recent call last):
File "/home/pi/escape/listings/listings/listing7-2.py", line 7, in <module>
player = Bluecar.png
NameError: name 'Bluecar' is not defined.

Also, after fixing the NameError, I think an Attribute Error will occur.


Solution

  • You probably want to use the pygame.image.load() function

    import pygame, time
    import os.path
    
    pygame.init()
    (width, height) = (300, 200)
    screen = pygame.display.setmode((width, height))
    pygame.display.flip()
    
    filepath = os.path.dirname(__file__)
    x = 0 #x co-ordinate
    y = 0 #y co-ordinate
    player = pygame.image.load(os.path.join(filepath, "Bluecar.png"))
    screen.blit(player, (x, y))
    

    Edit

    Included os.path.join to ensure image loaded from the directory of the python file.