Python点击文本定义的矩形时为什么会返回AttributeError?

huangapple go评论75阅读模式
英文:

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()):

huangapple
  • 本文由 发表于 2023年5月26日 00:36:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76334501.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定