为什么会出现这个nameError

Why is this nameError occurring

我今年9岁,正在自学,请亲们回复时谨记这一点,非常感谢您的宝贵时间。

我在同一个文件中有图像 Bluecar.png 和以下代码:

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)

但是,它会导致这个错误:

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.

另外,修复NameError后,我认为会出现Attribute Error。

您可能想使用 pygame.image.load() 函数

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))

编辑

包含 os.path.join 以确保从 python 文件的目录加载图像。