Pygame:AttributeError:'NoneType'对象没有属性'fill'

问题描述

所以,这是我的代码,我通过观看教程正常编码,但是当我使用填充属性时,突然出现一个错误内容如下:

第 15 行,在 display.fill((25,25,29)) AttributeError: 'nonetype' 对象没有属性 'fill'

下面是我写的代码,如果有人愿意帮助我,我会很高兴!

下面是我的代码

import pygame

pygame.init()

pygame.display.set_mode((800,600))

display = pygame.display.set_caption("Space Invaders!")

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

display.fill((25,29))
pygame.display.update()

解决方法

虽然我没有 pygame,所以无法测试代码,但我强烈怀疑您的问题与这三行以及它们之间的关系有关:

pygame.display.set_mode((800,600))

display = pygame.display.set_caption("Space Invaders!")

display.fill((25,25,29))

您已经设置了显示模式,现在要填充它。但是,您实际上并未将 display.set_mode() 的输出分配给 display,而是将 display.set_caption() 的输出分配给了 - 正如其他人已经评论过的那样,这与 {{ 1}} 不返回值。

因此,当您尝试使用 display.set_caption() 时,它不包含任何内容。

考虑尝试以下代码(虽然我不知道顺序是否重要):

display
,

我怀疑 pygame 初始化失败。这传播到:

display = pygame.display.set_caption("Space Invaders!")

返回“NoneType”对象,该对象在您运行时最终失败:

display.fill((25,29))

在“display =...”处使用断点查看返回值。

在进一步查看之后......它与语法/格式相关。以下是我进行的更正:

import pygame

pygame.init()

screen = pygame.display.set_mode((800,600))
display = pygame.display.set_caption("Space Invaders!")

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        screen.fill((25,29))
        pygame.display.update()