【问题标题】:AttributeError: object has no attribute rectAttributeError:对象没有属性矩形
【发布时间】:2014-04-03 03:38:33
【问题描述】:

我从我的代码中得到一个错误,我不知道为什么,但在语法上,我猜是正确的

import pygame

class BaseClass(pygame.sprite.Sprite):
    allsprites = pygame.sprite.Group()  
    def __init__(self, x, y, width, height, image_string):
        pygame.sprite.Sprite.__init__(self)
        BaseClass.allsprites.add(self)

        self.image = pygame.image.load("Images\lebron.png")
        self.rectangle = self.image.get_rect()
        self.rectangle.x = x
        self.rectangle.y = y
        self.width = width
        self.height = height

class Lebron(BaseClass):
    List = pygame.sprite.Group()
    def __init__(self, x, y, width, height, image_string):
        BaseClass.__init__(self, x, y, width, height, image_string)
        Lebron.List.add(self)
        self.velx = 0

    def movement(self):
        self.rectangle.x += self.velx

所以如果我把它编译到我的主文件中,下面的代码

import pygame, sys
from classes import *
from process import process

pygame.init()
WIDTH, HEIGHT = 640, 360
screen = pygame.display.set_mode((WIDTH, HEIGHT))

clock = pygame.time.Clock()
FPS = 24

lebron = Lebron(0, 100, 104, 120, "Images\lebron.png")

while True:
    process()
    #LOGIC
    lebron.movement()
    #LOGIC

    #DRAW
    BaseClass.allsprites.draw(screen)
    screen.fill((0,0,0))
    pygame.display.flip()
    #DRAW

    clock.tick(FPS)

我收到一个错误,即属性错误:Lebron 对象没有属性 rect。怎么了?回溯:

Traceback (most recent call last):
 File "MAIN.py", line 24, in <module>
   BaseClass.allsprites.draw(screen)
 File "C:\Python27\lib\site-packages\pygame\sprite.py", line 409, in draw
   self.spritedict[spr] = surface_blit(spr.image, spr.rect)
 AttributeError: 'Lebron' object has no attribute 'rect' 

【问题讨论】:

  • 哪一行产生错误?你能提供错误的完整追溯吗?
  • PyGame 可能会尝试调用您的对象的 rect() 或以其他方式访问位于 rect 属性方法时它没有 - 请参阅 pygame.org/docs/ref/rect.html (和鲁本关于回溯的权利)跨度>
  • 代码为BaseClass.allsprites.draw(screen)的那个
  • Traceback(最近一次调用最后):文件“MAIN.py”,第 24 行,在 BaseClass.allsprites.draw(screen) 文件“C:\Python27\lib\site-packages \pygame\sprite.py",第 409 行,在 draw self.spritedict[spr] = surface_blit(spr.image, spr.rect) AttributeError: 'Lebron' object has no attribute 'rect'
  • 好的,所以你的对象没有提供 PyGame 似乎需要的一些 rect 属性或方法。

标签: python pygame attributeerror


【解决方案1】:

它出现在发布的回溯上(当您在4个空格中缩进时,它们看起来更好,甚至更好地编辑问题包含它们)PyGame Draw()方法期望您的属性提供rect属性。在猜测中,如果替换rectangle 987654323 @,您将至少取得一些进度。

基本上,pygame想要绘制您的对象,但无法了解如何。

【讨论】:

  • 哦,成功了。太感谢了!抱歉那个缩进的事情,我在这里是新的:) span>
  • 这就是我们所有人都必须开始。很高兴它帮助了。我已经编辑了一个问题,以包括未来参考的回溯。 span>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-05
  • 2016-05-09
  • 2015-05-07
  • 2020-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多