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

topleft from surface rect dont accept new tuple value

I create pygame screen.

import pygame

pygame.init()
screen = pygame.display.set_mode((330, 330))

Then i create an object of my own class and give him a tuple.

mc = MyClass((10, 10))

This class has a problem. topleft from surface don`t accept new tuple value.

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

class MyClass:
    def __init__(self, pos):
        self.surface = pygame.Surface((100, 100))
        self.surface.get_rect().topleft = pos

        print(pos) # (10, 10)
        print(self.surface.get_rect().topleft) # (0, 0)

How can i solve this problem?

>Solution :

A Surface has no position and the rectangle is not an attribute of the Surface. The get_rect() method creates a new rectangle object with the top left position (0, 0) each time the method is called. The instruction

self.surface.get_rect().topleft = pos

only changes the position of an object instance that is not stored anywhere. When you do

print(self.surface.get_rect().topleft)

a new rectangle object will be created with the top left coordinate (0, 0). You have to store this object somewhere. Then you can change the position of this rectangle object instance:

class MyClass:
    def __init__(self, pos):
        self.surface = pygame.Surface((100, 100))
        self.rect = self.surface.get_rect()
        self.rect.topleft = pos
        print(self.rect.topleft) 
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