Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

AttributeError when trying to use the pygame.Rect.scale_by() method

Python script:

import pygame
left, top, width, height = 0, 0, 1, 1
my_rect = pygame.Rect(left, top, width, height)
my_rect.scale_by(2)

Result in terminal:

pygame 2.2.0 (SDL 2.0.22, Python 3.8.8)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'pygame.rect.Rect' object has no attribute 'scale_by'

According to the documentation, scale_by() is a method of pygame.Rect: https://www.pygame.org/docs/ref/rect.html#pygame.Rect.scale_by

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

scale_by()

scale the rectangle by given a multiplier

scale_by(scalar) -> Rect

scale_by(scalex, scaley) -> Rect

Returns a new rectangle with the size scaled by the given multipliers. The rectangle remains centered around its current center. A single scalar or separate width and height scalars are allowed. Values above one will increase the size of the rectangle, whereas values between zero and one will decrease the size of the rectangle.

Why am I getting this error ? How can I make the scale_by() method work ?

Other methods like move() works perfectly fine in this context, but some like scale_by() does not and I cannot figure out why.

>Solution :

scale_by is implemented in Pygame 2.3.0 (see the release notes pygame 2.3.0). You have to do 2 things:

  1. upgrade to Pygame 2.3.0

    pip install pygame --upgrade
    
  2. use scale_by_ip instead of scale_by

    my_rect.scale_by_ip(2)
    

    or assign the return value of scale_by to my_rect

    my_rect = my_rect.scale_by(2) 
    

    Note, scale_by doesn’t scale the rectangle itselfe, but returns a new rectangle.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading