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

点击文本对应矩形时Python抛出AttributeError错误的原因

为什么触发AttributeError错误?

错误原因

t2r是通过t2.get_rect()获取的Rect对象,它本身就自带碰撞检测所需的collidepoint()方法。你在代码里错误地使用了t2r.rect.collidepoint(),但Rect对象并没有名为rect的子属性,这直接导致了AttributeError。

修正后的执行代码

running = True
while running:
    events = pygame.event.get()
    for event in events:
            if event.type == pygame.MOUSEBUTTONDOWN:
                # 直接调用t2r的collidepoint方法即可
                if t2r.collidepoint(pygame.mouse.get_pos()):
                    print("hello")

补充说明

在Pygame中,Surface.get_rect()返回的就是Rect类的实例,用来对应Surface的矩形区域。所有和该区域相关的操作(比如碰撞检测、位置调整)都直接通过这个Rect对象调用方法或属性,无需额外添加.rect后缀。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 22:13:15