我创建pygame屏幕
import pygame
pygame.init()
screen = pygame.display.set_mode((330, 330))
然后我创建一个我自己的类的对象,并给他一个元组。
mc = MyClass((10, 10))
这个类有一个问题.topleft
fromsurface
不接受新的元组值
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)
我该如何解决这个问题?
ASurface没有位置,矩形也不是Surface的属性。get_rect()
方法每次调用时都会创建一个新的矩形对象,其左上角位置为(0,0)。. 指令
self.surface.get_rect().topleft = pos
仅更改没有存储在任何地方的对象实例的位置。当你做
print(self.surface.get_rect().topleft)
将创建一个新的矩形对象,其左上角坐标为(0,0)。您必须将该对象存储在某个地方。然后你可以改变这个矩形对象实例的位置:
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)