Pygame NameError:未定义名称'image'

时间:2018-01-13 17:21:30

标签: python pygame

我正在修改我在网上找到的程序,我正在尝试加载.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

1 个答案:

答案 0 :(得分:4)

image.self.pygame ("Sprite-01.png")

将该行更改为:

self.image = pygame.image.load("Sprite-01.png").convert_alpha()
如果图片没有透明部分,则

或仅.convert()

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