点击文本对应矩形时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
相关产品推荐
相关产品推荐

