0

When using surface.blit during a mouse event, the blit doesn't remain on the screen.

I have two almost identical images. The standard image already exists on the surface and when the mouse hovers over the image, another image needs to be placed on top of the existing image and when the mouse leaves the image it needs to be removed.

My current code works except a mouse event needs to be going on - when the mouse is stationary inside the image, the overlay image is removed. How do I fix this?

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

Note: The Execute() function is a method within the class App.

nx_prv
  • 127
  • 8

1 Answers1

1

Your code currently only does its mouse position checking inside a loop over the events that have been generated during the frame. That means it won't run if there are no events. Try moving that code outside of the for Event in pygame.event.get() loop, and it will run once a frame, regardless of the event status.

Note that you probably do want to deal with events, but you're not doing so now. If you really don't care about any events (not even the QUIT event?), you could replace looping over the events with a call to pygame.events.pump(), which will let Pygame handle any internal events (like dragging or resizing the window), without sending anything to you.

Blckknght
  • 100,903
  • 11
  • 120
  • 169