E
E
ere1232022-02-23 20:18:15
pygame
ere123, 2022-02-23 20:18:15

Can't create a character using a class?

from pygame import *
window = display.set_mode((600, 600))
display.set_caption("Шлёпа")
class Flopa(sprite.Sprite):
    def __init__(self, image, x, y,):
        sprite.Sprite.__init__(self)
        self.image = transform.scale(image.load("flopa.png"), (50, 50))
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
    def update(self):
        keys = key.get_pressed()
        if keys[K_LEFT]:
            self.rect.x -= 5
        if keys[K_RIGHT]:
            self.rect.x += 5
run = True
while run:
    for e in event.get():
        if e.type == KEYDOWN:
            if e.key == K_ESCAPE: 
                run = False 
    flopa = Flopa(("flopa.png"), 100, 100)
    flopa.update()
    window.fill((250,250,250))
    time.delay(20)
    display.update()

self.image = transform(image.load("flopa.png"), (50, 50))
AttributeError: 'str' object has no attribute 'load'

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
YariKartoshe4ka, 2022-02-24
@YariKartoshe4ka

From the PEP8 standard:

Wildcard imports ( from module import * ) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools

You have a "naming conflict" and pygame.image is replaced by an argument with the same name image in the constructor:
def __init__(self, image, x, y,): # Redefinition of pygame.image

I
Ivan Chetchasov, 2022-02-26
@TalismanChet

You are using image as an argument to Flopa.__init__,
just change to and instead of
def __init__(self, image, x, y,):
def __init__(self, _image, x, y,):

self.image = transform.scale(image.load("flopa.png"), (50, 50))

use
self.image = transform.scale(image.load(_image), (50, 50))

Also, you have an extra comma here:
def __init__(self, image, x, y>>,<<)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question