-->

self.rect not found?

2019-08-29 08:54发布

问题:

I have a program that is simply made to move an image around. I try to state the self.rect as part of a load_png() call, but it simply does not like it. THe reason I think this will work is from http://www.pygame.org/docs/tut/tom/games6.html, saying that this should work:

def __init__(self, side):
            pygame.sprite.Sprite.__init__(self)
            self.image, self.rect = load_png('bat.png')
            screen = pygame.display.get_surface()
            self.area = screen.get_rect()
            self.side = side
            self.speed = 10
            self.state = "still"
            self.reinit()

Here is my code, which according to the pygame tutorial from its own website, should work:

def _init_(self):
    pygame.sprite.Sprite._init_(self)
    self.state = 'still'
    self.image =  pygame.image.load('goodGuy.png')
    self.rect = self.image.get_rect()       
    screen = pygame.display.getSurface()

And it gives me this error:

Traceback (most recent call last):
File "C:\Python25\RPG.py", line 37, in <module>
screen.blit(screen, Guy.rect, Guy.rect)
AttributeError: 'goodGuy' object has no attribute 'rect'

If you guys need all of my code, comment blew and I will edit it.

回答1:

You don't have a load_png function defined.

You need to create the pygame image object before you can access its rect property.

self.image = pygame.image.load(file)

Then you can assign the rect value using

self.rect = self.image.get_rect()

Or you could create the load_png function as per the example you linked.



回答2:

There is no load_png function built-in to python or pygame. I imagine that the tutorial you are referring to defined it manually somewhere. What you want is pygame.image.load(filename) and then you can call get_rect() on the returned Surface object. The complete code would be as follows:

self.image = pygame.image.load('bat.png')
self.rect = self.image.get_rect()

Your second problem is that you've defined the function _init_, but you need double underscores: __init__.

Also, you need to post the code where the error is actually occurring.