【问题标题】:why the attribute error arise while doing pygame为什么在做pygame时会出现属性错误
【发布时间】:2021-07-10 03:57:48
【问题描述】:

我在pygame的学习阶段,python代码显示属性错误 这是代码

import pygame
from pygame.locals import (
    K_DOWN,
    K_UP,
    K_LEFT,
    K_RIGHT,
    K_ESCAPE,
    KEYDOWN,
    QUIT)
pygame.init()#initailaze the window
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
screen_display = pygame.display.set_mode([SCREEN_WIDTH , SCREEN_HEIGHT])
#variable to keep loop running
running = True
#main loop begins here
while running:
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                running = False
        elif event.type == QUIT:
             running = False
    screen_display = screen_display.fill((255,255,255))
    surface = pygame.Surface((50,50))
    surface.fill((0,0,0))
    rectangle = surface.get_rect()
    screen_display.blit(surface, (SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
    pygame.display.flip()

pygame.quit()

#输出如下

pygame 2.0.1 (SDL 2.0.14, Python 3.7.9)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "G:\project\game\start.py", line 27, in <module>
    screen_display.blit(surface, (SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
AttributeError: 'pygame.Rect' object has no attribute 'blit'

【问题讨论】:

  • screen_display = pygame.display.set_mode([SCREEN_WIDTH , SCREEN_HEIGHT]) 返回一个 pygame.Surface 对象。 screen_display = screen_display.fill((255,255,255)) 返回一个 pygame.Rect 对象。 pygame.Rect 没有 blit 属性,因此出现错误。

标签: python pygame


【解决方案1】:

问题是由线条引起的

screen_display = screen_display.fill((255,255,255))

在这一行中,您将screen_display.fill 的返回值重新分配给变量screen_displaypygame.Surface.fill 的返回值是一个 pygame.Rect 对象,包括受影响的 Surface 区域。

更改指令:

screen_display = screen_display.fill((255,255,255))

screen_display.fill((255,255,255))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    相关资源
    最近更新 更多