【问题标题】:Why is this nameError occurring为什么会出现这个nameError
【发布时间】:2020-07-03 17:37:18
【问题描述】:

我 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后,我认为会出现属性错误。

【问题讨论】:

  • 好吧,Bluecar 没有定义。你的意思是player = "Bluecar.png"
  • 然后我在 screen.blit(player) 上有一个 TypeError:
  • 参数 1 必须是 pygame.surface,而不是 str
  • 您有想要使用的名为Bluecar.png 的图像文件吗?据推测,您需要一些函数来加载给定文件的str 名称的图像,然后 that 将是blit 的第一个参数。
  • 我在同一个文件夹中有图片文件

标签: python python-3.x file pygame nameerror


【解决方案1】:

您可能想使用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文件的目录加载图像。

【讨论】:

  • 尝试导致 pygame.error: 无法打开 Bluecar.png。对不起
  • 已编辑以确保从与 python 文件相同的目录中读取图像。
  • screen = pygame.display.setmode((width, height)) has an Attribute error: modulepygame.display has no attribute 'setmode'
  • 和一个空白的pygame窗口(全黑)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 2012-01-31
  • 2020-02-03
  • 1970-01-01
相关资源
最近更新 更多