英文:
Why does python return an AttributeError when I click on a rectangle defined by a text?
问题
以下是翻译好的部分:
我希望我的代码在我点击文本时做出反应。这是定义文本/矩形的代码:
t2 = font.render("YOU ARE BORN", True, "Black", "white")
t2r = t2.get_rect()
t2r.center = (SCREEN_WIDTH/2, SCREEN_HEIGHT/2)
这是执行代码的部分:
running = True
while running:
events = pygame.event.get()
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN:
if t2r.collidepoint(pygame.mouse.get_pos()):
print("hello")
运行时,我收到以下错误信息:
AttributeError: 'pygame.rect.Rect' object has no attribute 'rect'
英文:
I want my code to react when I click on a text. This is my code defining the text/rectangle:
t2 = font.render("YOU ARE BORN", True,"Black", "white")
t2r = t2.get_rect()
t2r.center = (SCREEN_WIDTH/2, SCREEN_HEIGHT/2)
And this is where it is executed:
running = True
while running:
events = pygame.event.get()
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN:
if t2r.rect.collidepoint(pygame.mouse.get_pos()):
print("hello")
And when this is run I get this error:
if t2r.rect.collidepoint(pygame.mouse.get_pos()):
AttributeError: 'pygame.rect.Rect' object has no attribute 'rect'
答案1
得分: 2
t2r
已经是一个 pygame.Rect
对象,所以只需使用 t2r.collidepoint
,而不是 t2r.rect.collidepoint
:
if t2r.rect.collidepoint(pygame.mouse.get_pos()):
if t2r.collidepoint(pygame.mouse.get_pos()):
英文:
t2r
is already a pygame.Rect
object. So just t2r.collidepoint
instead of t2r.rect.collidepoint
:
<s>if t2r.rect.collidepoint(pygame.mouse.get_pos()):
</s>
if t2r.collidepoint(pygame.mouse.get_pos()):
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论