Pygame 属性错误:没有 'display' 属性

0 投票
1 回答
2532 浏览
提问于 2025-04-18 09:22

我正在学习Python和Pygame,想通过制作一个2D的砖块平台游戏来练习。目前我在“砖块”这部分遇到了困难。这是我的代码:

import pygame, sys
from pygame.locals import *

#Just defining some variables
windowWidth = 640
windowHeight = 480
mapWidth = windowWidth // 32
mapHeight = windowHeight // 32
tilesize = 32
speed = [1, 1] #Array/List declaration
black = (0,0,0) #Tuple declaration

#intended to create a 2d list of subsurfaces    
def create_map():
    floor = pygame.image.load("rect_gray0.png")
    map = []
    for x in range(mapWidth):
        line = []
        map.append(line)
        for y in range(mapHeight):
            line.append(floor.subsurface((0,0,tilesize,tilesize)))

    return map


if __name__ == '__main__':

    pygame.init()
    print("Initializing")

    screen = pygame.display.set_mode((windowWidth, windowHeight))
    map = create_map()

    while 1:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        screen.fill(black)

        for x in range(mapWidth):
            for y in range(mapHeight):
                #for each subsurface in the map, blit it to the screen.
                tile = map[x][y]
                screen.blit(tile, (x*tilesize, y*tilesize))

        screen.display.flip() 

当我运行这段代码时,出现了这个错误:

Traceback (most recent call last):
  File "C:\Users\dementeddr\workspace\TheWaterIsRising\src\default\RisingMain.py", line 59, in <module>
    screen.display.flip() 
AttributeError: 'pygame.Surface' object has no attribute 'display'

我在网上查了很多,看到过很多其他的属性错误,但没有找到关于'display'属性的内容。我到底哪里出错了呢?

1 个回答

1

这个错误信息告诉你所有需要知道的事情:

Traceback (most recent call last):
  File "C:\Users\dementeddr\workspace\TheWaterIsRising\src\default\RisingMain.py", line 59, in <module>
    screen.display.flip() 

上面的部分显示了出问题的代码行,就是 screen.display.flip()

AttributeError: 'pygame.Surface' object has no attribute 'display'

screen 是一种 pygame.Surface 类型的东西,但它没有 display 这个属性,所以肯定是哪里出了问题。查看一下教程,比如这个 http://www.pygame.org/docs/tut/intro/intro.html,你会发现应该用 pygame.display.flip() 来代替。试着把那行代码换掉,看看能不能正常运行。

祝你好运 :)

撰写回答