【问题标题】:Pygame NameError: name 'image' is not definedPygame NameError:名称“图像”未定义
【发布时间】:2018-01-14 18:45:19
【问题描述】:

我正在修改我在网上找到的一个程序,我正在尝试加载一个 .png 而不是以前的块精灵,但我认为我在尝试加载它时编码不正确。代码如下:

class Player(pygame.sprite.Sprite):
    """
    This class represents the bar at the bottom that the player controls.
    """

    # -- Methods
    def __init__(self):
        """ Constructor function """

        # Call the parent's constructor
        super().__init__()

        # Create an image of the block, and fill it with a color.
        # This could also be an image loaded from the disk.
        image.self.pygame ("Sprite-01.png")

        # Set a referance to the image rect.
        self.rect = self.image.get_rect()

        # Set speed vector of player
        self.change_x = 0
        self.change_y = 0

        # List of sprites we can bump against
        self.level = None

这是错误:

Traceback (most recent call last):   

File "C:/Users/1234/AppData/Local/Programs/Python/Python36-32/class 10 program St.Patrick.py", line 452, in <module>
    main()   
File "C:/Users/1234/AppData/Local/Programs/Python/Python36-32/class 10 program St.Patrick.py", line 360, in main
    player = Player()   
File "C:/Users/1234/AppData/Local/Programs/Python/Python36-32/class 10 program St.Patrick.py", line 51, in __init__
    image.self.pygame ("Sprite-01.png") 
NameError: name 'image' is not defined

【问题讨论】:

    标签: python pygame


    【解决方案1】:
    image.self.pygame ("Sprite-01.png")
    

    将该行更改为:

    self.image = pygame.image.load("Sprite-01.png").convert_alpha()
    

    如果图像没有透明部分,则只需 .convert()

    我还建议在程序启动之前将图像加载到全局范围或其他模块中,然后重用它们而不是再次加载它们。从硬盘读取速度很慢。

    【讨论】:

    • 现在我明白了:
    • 回溯(最近一次调用最后):文件“C:/Users/1234/AppData/Local/Programs/Python/Python36-32/class 10 program St.Patrick.py”,第 452 行,在 main() 文件“C:/Users/1234/AppData/Local/Programs/Python/Python36-32/class 10 程序 St.Patrick.py”中,第 360 行,在 main player = Player() 文件中“ C:/Users/1234/AppData/Local/Programs/Python/Python36-32/class 10 程序 St.Patrick.py",第 51 行,在 init self.image = pygame.image.load ("Sprite-01.png").convert_alpha() pygame.error: 无法打开 Sprite-01.png
    • 你必须通过正确的路径。图片在哪个目录?并检查图片名称是否正确。
    • 这里我描述了如何构建路径:stackoverflow.com/a/47082774/6220679 如果图像位于“图像”目录中,您也可以只使用"images/Sprite-01.png"
    • 尝试将“Sprite-01.png”文件与您用于启动游戏的 .py 文件放在同一目录中,然后尝试再次使用self.image = pygame.image.load("Sprite-01.png").convert_alpha() 加载它。跨度>
    猜你喜欢
    • 1970-01-01
    • 2015-05-05
    • 2018-11-27
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    相关资源
    最近更新 更多