"Object has not attribute "get_width" in Python

This was a simple task of placing an image on the screen. It worked. I decided to start trying to make a class. Now it does not work. The error I get:
Traceback (most recent call last):
Group\Science\python\Photosynthesis\Photosynthesis.py", line 37, in <module>
Equipment_img = Myexperiment(50, 50, Equipment_img, 1.0)
File "c:\Users\Owner\Documents\Glamorgan Fungus Group\Science\python\Photosynthesis\Photosynthesis.py", line 17, in __init__
width = image.get_width()
I think this error is just going to continue to the next line... I think the error has to do with surfaces but I would be lying if I said I knew entirely what that means.
Tried simplifying the class but I just kept throwing up errors. I know this is me fundamentally not grasping something in Python. Hoping for a Eureka moment.
import pygame
pygame.init()
#Display Window
SCREEN_HEIGHT = 800
SCREEN_WIDTH = 1200
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Photosynthesis')
Equipment_img = pygame.image.load("whole_experiment.png").convert_alpha()
#Load up the Images of the experiment
class Myexperiment ():
def __init__ (self, x, y, image, scale):
width = image.get_width()
height = image.get_height()
self.image = pygame.transform.scale(image, (int(width*scale), int(height*scale)))
self.rect = self.image.get_rect()
self.rect.topleft = (x, y)
def draw(self):
screen.blit(self.image, (self.rect.x, self.rect.y))
#The Game loop as always.
run = True
while run:
screen.fill((202, 228, 241))
Equipment_img = Myexperiment(50, 50, Equipment_img, 1.0)
#Event handler
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.update()
pygame.quit()
Answer
You're rebinding the name Equipment_img
in your main loop. The first time through, it likely works as you intend, because the initial value in that variable is an image. The second time (and subsequent times, if it could get that far), you pass a Myexperiment
instance instead of an image.
It's not exactly clear what you want to have happen here, since you never do anything with the instance of your class, but you probably want to create the Myexperiment
instance outside of the loop, and just call its draw
method inside the loop. I'd also suggest using a different variable name so that this kind of mistaken use of one object where another is intended can't happen.
Abbreviated code:
Equipment_img = pygame.image.load("whole_experiment.png").convert_alpha()
# move this line out of the loop, and assign to a different variable name too
experiment = Myexperiment(50, 50, Equipment_img, 1.0)
while True:
experiment.draw() # do something with the instance, rather than recreating it
Enjoyed this article?
Check out more content on our blog or follow us on social media.
Browse more articles