Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error in self.rect = self.image.get_rect()

Help, an error occurs when compiling:

The error occurs here self.rect = self.image.get_rect()

AttributeError: 'str' object has no attribute 'get_rect'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class GameSprite(sprite.Sprite):
    def __init__(self, image, speed, x, y):
        super().__init__()
        self.image = image
        self.speed = speed
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

>Solution :

image is a filename. You need to load the image from the file with pygame.image.load:

class GameSprite(sprite.Sprite):
    def __init__(self, filename, speed, x, y):
        super().__init__()
        self.image = image.load(filename)
        self.rect = self.image.get_rect(topleft = (x, y))
        self.speed = speed

However, I recommend to import pygame instead of from pygame import *:

import pygame

class GameSprite(pygame.sprite.Sprite):
    def __init__(self, filename, speed, x, y):
        super().__init__()
        self.image = pygame.image.load(filename)
        self.rect = self.image.get_rect(topleft = (x, y))
        self.speed = speed
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading