You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pygame报错:'pygame.Rect'对象无'origin'属性,原点设置失败

解决Pygame中AttributeError: 'pygame.Rect' object has no attribute 'origin'错误

问题根源

你犯了两个关键错误:

  • Pygame的surface.get_rect()方法根本没有origin这个参数,直接传origin=(x,y)会触发属性错误
  • 你传入的midtop锚点参数完全没被用到,等于白传了

正确的实现方式

Pygame的get_rect()支持直接通过锚点名称作为关键字参数来定位,比如要把矩形的midtop放在(x,y),直接传midtop=(x,y)就行。我们可以利用字典解包来动态使用传入的origin参数:

修正后的代码:

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))

class Rectangle:
    def __init__(self, image, alpha, origin, x, y):
        # 优化:只加载一次图片,避免重复IO
        if alpha:
            self.surface = pygame.image.load(image).convert_alpha()
        else:
            self.surface = pygame.image.load(image).convert()
        # 动态使用传入的origin锚点定位
        self.rectangle = self.surface.get_rect(**{origin: (x, y)})

    def setpos(self, x, y):
        self.rectangle.x = x
        self.rectangle.y = y

    def place(self):
        screen.blit(self.surface, self.rectangle)

# 测试:将图片的midtop定位在(0,0)
test = Rectangle('image.png', 1, 'midtop', 0, 0)

额外说明

  • 如果需要修改锚点位置,也可以直接操作rect的属性,比如self.rectangle.midtop = (new_x, new_y),比单独改x、y更准确
  • 确保初始化Pygame和创建screen对象,否则screen.blit会报错

内容的提问来源于stack exchange,提问作者Jibhong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 18:42:38