Reputation: 13
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
Upvotes: 0
Views: 265
Reputation: 210946
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
Upvotes: 1