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

Question:

Help, an error occurs when compiling:

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

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

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
Asked By: Taras Palamarchuk

||

Answers:

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
Answered By: Rabbid76
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.