如何在Pygame Sprite类中使用参数作为pygame.Surface.get_rect()的关键字参数?
解决Pygame Sprite类多坐标锚点的问题
你遇到的NameError是因为误将midtop这类锚点名称当作变量使用,实际上它们是字符串类型的Rect属性名。Pygame的get_rect()方法需要的是midtop=(x,y)这种关键字参数形式,而非直接传递未定义的变量。
正确实现方式
通过字典解包的方式,将origin参数(字符串类型的锚点名)和坐标pos组合成关键字参数,传递给get_rect()方法,就能支持任意合法的Rect锚点属性。
示例代码如下:
import pygame class MySprite(pygame.sprite.Sprite): def __init__(self, size, color, pos, origin='bottomleft', groups=None): super().__init__(groups or []) # 创建精灵表面并填充颜色 self.image = pygame.Surface(size) self.image.fill(color) # 用字典解包传递锚点参数 self.rect = self.image.get_rect(**{origin: pos})
调用示例
pygame.init() screen = pygame.display.set_mode((800, 600)) all_sprites = pygame.sprite.Group() # 以midtop为锚点创建红色精灵 sprite1 = MySprite((50,50), (255,0,0), (400,50), origin='midtop', groups=all_sprites) # 以center为锚点创建绿色精灵 sprite2 = MySprite((50,50), (0,255,0), (400,300), origin='center', groups=all_sprites) # 默认bottomleft锚点创建蓝色精灵 sprite3 = MySprite((50,50), (0,0,255), (100,550), groups=all_sprites) # 游戏循环示例 running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False screen.fill((30,30,30)) all_sprites.draw(screen) pygame.display.flip() pygame.quit()
注意事项
- origin参数必须传入Pygame Rect对象支持的属性名字符串,可选值包括:
top、topleft、topright、midtop、center、midleft、midright、bottom、bottomleft、bottomright。 - 代码中给origin设置了默认值
bottomleft,兼容你最初的实现逻辑。
内容的提问来源于stack exchange,提问作者RobotZap10000
相关产品推荐
相关产品推荐

