I
I
Ivan Demianov2020-10-02 17:57:12
Python
Ivan Demianov, 2020-10-02 17:57:12

Error in Pygame: AttributeError: 'str' object has no attribute 'image'. What to do?

I am writing a game Labyrinth on PyGame, here is the code:

import pygame
import random
import os
import time

# настройка папки ассетов
game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, 'img')
player_img = pygame.image.load(os.path.join(img_folder, '/Users/polina/Desktop/PyGame/img/кіт3.png'))
player_img2 = pygame.image.load('/Users/polina/Desktop/PyGame/img/bg.png')
WIDTH = 2000
HEIGHT = 900
FPS = 30

# Задаем цвета
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)


class Player(pygame.sprite.Sprite):     
    
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = player_img
        self.rect = self.image.get_rect()
        self.rect.center = (WIDTH / 2, HEIGHT / 2)
    def update(self):
        self.speedx = 0
        keystate = pygame.key.get_pressed()
        if keystate[pygame.K_LEFT]:
            self.speedx -= 8
        if keystate[pygame.K_RIGHT]:
            self.speedx += 8
        if keystate[pygame.K_UP]:
            self.rect.y -= 8
        if keystate[pygame.K_DOWN]:
            self.rect.y += 8
        self.rect.x += self.speedx
class Wall(pygame.sprite.Sprite):
    def init(self):
        pygame.sprite.Sprite.__init__(self)
        self.fill(BLACK)
        self.rect = self.image.get_rect()
        self.rect.center = (WIDTH / 2, HEIGHT / 2)
    def create(self,colour,x,y):
        self.image.fill(colour)
        self.rect.y = y
        self.rect.x = x   
        self.rect.width = 10
        self.rect.height = 10
# Создаем игру и окно
        
pygame.init()
pygame.mixer.init()
Wall.create("",GREEN,0,0)
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Test Game ")
clock = pygame.time.Clock()
all_sprites = pygame.sprite.Group()
player = Player()
pl = Wall()
all_sprites.add(player)
all_sprites.add(pl)

# Цикл игры
running = True
while running:
    # Держим цикл на правильной скорости
    clock.tick(FPS)
    # Ввод процесса (события)
    for event in pygame.event.get():
        # check for closing window
        if event.type == pygame.QUIT:
            running = False

    # Обновление
    all_sprites.update()
    
    # Рендеринг
    screen.fill(RED)
    screen.blit(player_img2, (0,0))
    all_sprites.draw(screen)
    # После отрисовки всего, переворачиваем экран
    pygame.display.flip()

pygame.quit()

Ошибка: Traceback (most recent call last):
  File "/Users/polina/Documents/PyGameTest1.py", line 58, in <module>
    Wall.create("", GREEN, 0, 0)
  File "/Users/polina/Documents/PyGameTest1.py", line 49, in create
    self.image.fill(colour)
AttributeError: 'str' object has no attribute 'image'
Что делать? Какие дальше могут быть ошибки? Как их исправить?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Ternick, 2020-10-02
@Vanushka1102

The error occurs in the create method of the Wall class:

class Wall(pygame.sprite.Sprite):
    def init(self):
        pygame.sprite.Sprite.__init__(self)
        self.fill(BLACK)
        self.rect = self.image.get_rect()
        self.rect.center = (WIDTH / 2, HEIGHT / 2)
    def create(self,colour,x,y):
        self.image.fill(colour) #Тута
        self.rect.y = y
        self.rect.x = x   
        self.rect.width = 10
        self.rect.height = 10

Because of this challenge:
Wall.create("",GREEN,0,0)
Because someone climbed into a place where they don't understand anything.
self is not just a parameter, but much more important, it does not need to be passed from outside. {self is needed to work with internal class variables}
I don't know what further errors will fall, I'm not a wang, but an ordinary person.
Solution:
Go look at least something like self and why it is needed.
Replace the call to the create method of the Wall class with this Wall.create(GREEN,0,0).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question