Detecting a mouse on an image in Pygame

I have an image:

newGameButton = pygame.image.load("images/newGameButton.png").convert_alpha() 

Then I will display it on the screen:

 screen.blit(newGameButton, (0,0)) 

How to determine if a mouse is touching an image?

+4
source share
2 answers

Use Surface.get_rect to get a Rect describing the borders of your Surface , then use .collidepoint() to check if the mouse cursor is inside the Rect .


Example:

 if newGameButton.get_rect().collidepoint(pygame.mouse.get_pos()): print "mouse is over 'newGameButton'" 
+11
source

I'm sure there are more pythonic ways for this, but here is a simple example:

 button_x = 0 button_y = 0 newGameButton = pygame.image.load("images/newGameButton.png").convert_alpha() x_len = newGameButton.get_width() y_len = newGameButton.get_height() mos_x, mos_y = pygame.mouse.get_pos() if mos_x>button_x and (mos_x<button_x+x_len): x_inside = True else: x_inside = False if mos_y>button_y and (mos_y<button_y+y_len): y_inside = True else: y_inside = False if x_inside and y_inside: #Mouse is hovering over button screen.blit(newGameButton, (button_x,button_y)) 

Read more about the mouse in pygame , as well as the surface in pygame .

Also here is an example close to this.

+2
source

All Articles