Pygame for 循环中的游标仅适用于最后一个

Pygame cursor in for loop only working on last

我正在尝试在 pygame(python 模块)中切换光标,当鼠标围绕存储在列表中的矩形然后鼠标恢复正常时。

我测试了循环,它以多种方式工作。但是打开光标,只有列表的最后一个元素有效(缩进没问题)。这很奇怪,我已经测试了很多东西但它不起作用。

这是我的代码:

pygame.init()

[...]

button = pygame.draw.rect(screen, white, (585, 424, 50, 50))
button2 = pygame.draw.rect(screen, white, (235, 274, 30, 30))
button3 = pygame.draw.rect(screen, white, (440, 311, 40, 40))
all_buttons = [button2, button3, button]

running = True
while running:

    screen.blit(background, (0, 0))

    for x in all_buttons:
        if x.collidepoint(pygame.mouse.get_pos()):
            pygame.mouse.set_cursor(*pygame.cursors.diamond)

        else:
            pygame.mouse.set_cursor(*pygame.cursors.arrow)

    pygame.display.flip()

我也测试过这个:

 def mouse_state(cursor_state):
    if cursor_state:
        pygame.mouse.set_cursor(*pygame.cursors.arrow)
    else:
        pygame.mouse.set_cursor(*pygame.cursors.diamond)

[...]

cursor_state = True
while running:
    for x in all_buttons:
        if x.collidepoint(pygame.mouse.get_pos()):
            cursor_state = False
        else:
            cursor_state = True

    mouse_state(cursor_state)

    pygame.display.flip()

问题是当光标不在 下一个 框中时,您不断将光标设置回箭头。

遍历您的算法:

  • 如果光标在box1
    • 将光标设置为菱形
  • 其他
    • 将光标设置为箭头
  • 如果光标在box2
    • 将光标设置为菱形
  • 其他
    • 将光标设置为箭头
  • 如果光标在box3
    • 将光标设置为菱形
  • 其他
    • 将光标设置为箭头

因此,除非您将鼠标悬停在最后一个框上,否则光标只会瞬间设置为菱形,然后在下一个框测试中重新设置。超过前 2 个框时,您可能永远看不到它的变化。

一种解决方法是当鼠标在任何框内时设置一个标志,然后使用该标志设置鼠标光标。