AttributeError: 'pygame.Surface' object has no attribute 'collidepoint'

Making a button for a menu screen. I had to adapt from an example online so I could use a custom image to work as a button. Rather than using,

play_button = pygame.Rect(50,100,200,50)

Heres what I have so far,

def main_menu():
    while True:
        #menu background
        menu_background = pygame.image.load('game graphics/menu.png')
        menu_background = pygame.transform.scale(menu_background, (screen_w,screen_h)).convert()
        screen.blit(menu_background,(0,0))
        #menu buttons
        mx, my = pygame.mouse.get_pos()
        
        play_button = pygame.image.load('game graphics/play_button.png').convert_alpha()
        play_button = pygame.transform.scale(play_button, (400,300))
        # play_button = pygame.Rect(50,100,200,50)
        screen.blit(play_button,(-50,200))
        
        
        if play_button.collidepoint((mx,my)):
            if click:
                game()

The error im getting is,

AttributeError: 'pygame.Surface' object has no attribute 'collidepoint'

All I want to do is have the image I have selected used as a button. What am I doing wrong?

>Solution :

The error you are getting is because the play_button variable is now a pygame.Surface object, which does not have a collidepoint() method. When you commented out the line play_button = pygame.Rect(50,100,200,50), you removed the button’s rect object, so it no longer has the collidepoint() method.

You need to define a rect object for your button, and then check if the mouse position collides with it. You can use the get_rect() method of the play_button surface to get its rect object, and then use the collidepoint() method to check if the mouse position is within the rect.

Here’s an example of how you can modify your code to achieve this:

play_button_rect = play_button.get_rect(topleft=(50, 100))
if play_button_rect.collidepoint((mx, my)):
    if click:
        game()

This will create a rect object that has the same position and size as the play_button surface, and then check if the mouse position collides with it.

Leave a Reply