【问题标题】:PyGame blit image disappears when no mouse event is fired?PyGame blit 图像在没有触发鼠标事件时消失?
【发布时间】:2019-08-05 01:17:23
【问题描述】:

在鼠标事件期间使用surface.blit 时,blit 不会保留在屏幕上。

我有两张几乎一模一样的图片。标准图像已经存在于表面上,当鼠标悬停在图像上时,需要在现有图像之上放置另一个图像,当鼠标离开图像时,需要将其移除。

我当前的代码可以正常工作,但需要进行鼠标事件 - 当鼠标在图像内静止时,覆盖图像会被移除。我该如何解决这个问题?

def Execute(self):
    while self.Running == True:

        NewGameButton = pygame.image.load("./Assets/Interface/newgame.png").convert_alpha()
        NewGameButtonHover = pygame.image.load("./Assets/Interface/newgame_hover.png").convert_alpha()

        self.Display.blit(NewGameButton, (460,260))

        pygame.display.flip()

        for Event in pygame.event.get():
            if NewGameButton.get_rect(topleft=(460,260)).collidepoint(pygame.mouse.get_pos()):
                self.Display.blit(NewGameButtonHover, (460,260))
            pygame.display.update()

    pygame.quit()

注意:Execute() 函数是 App 类中的一个方法。

【问题讨论】:

    标签: python python-3.x pygame pygame-surface


    【解决方案1】:

    您的代码目前仅在循环内对帧期间生成的事件进行鼠标位置检查。这意味着如果没有事件,它将不会运行。尝试将该代码移到 for Event in pygame.event.get() 循环之外,无论事件状态如何,它都会每帧运行一次。

    请注意,您可能确实想要处理事件,但您现在没有这样做。如果你真的不关心任何事件(甚至不关心 QUIT 事件?),你可以通过调用 pygame.events.pump() 来替换循环事件,这将让 Pygame 处理任何内部事件(比如拖动或调整窗口),而不向您发送任何内容。

    【讨论】:

    • 我将它移出循环,但仍然没有改变发生的情况。
    • 没关系,我也需要将pygame.display.update() 移出循环
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 2017-10-17
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    相关资源
    最近更新 更多