Search code examples
pythonpygame

How to change the cursor in Pygame to a custom image


I have a button in my Pygame program.
Whenever my cursor is hovering over the button, I want the cursor to change to this image (but it could be any custom image), which is different from the default pointer image for Pygame:

enter image description here

I already know how to get the position of the mouse and when it is pressed. I just don't know how to change the cursor.


Solution

  • In case you want to create and use your own colorfully customized cursor from an image (and display different cursors depending on where you are in the game, e.g. in the menu or "ingame").

    Here is the procedure:

    • set mouse visibility to false
    • create a customized image you want to use as cursor
    • create a rect from that customized cursor image
    • update the rects position to your (invisible) mouse position
    • draw the image at the location of the rect

    Here is a short code example:

    pygame.mouse.set_visible(False)
    cursor_img_rect = cursor_img.get_rect()
    
    while True:
        # in your main loop update the position every frame and blit the image    
        cursor_img_rect.center = pygame.mouse.get_pos()  # update position 
        gameDisplay.blit(cursor_img, cursor_img_rect) # draw the cursor