Python Forum

Full Version: pygame animated button with images
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Example of using images and pygame for buttons. (did not do the callback function part).
Just hover and click animation. Hope it will help someone.

import pygame

pygame.init()
pygame.font.init()

# Setup pygame screen
screen_size = (800, 600)
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption('Pygame Button')

# Setup some colors
screen_bg = 'ivory2'

# Set framerate
fps = 60
framerate = pygame.time.Clock()

# Load and define button images. Three states normal, hover, and pressed
normal = pygame.image.load('normal.png')
hover = pygame.image.load('hover.png')
pressed = pygame.image.load('pressed.png')

# change cursor on hover
hand = pygame.SYSTEM_CURSOR_HAND

# Create Button class
class Button:
    def __init__(self, image, pos, callback):
        '''
            Create a animated button from images
            self.callback is for a funtion for the button to do - set to None
        '''
        self.image = image
        self.rect = self.image.get_rect(topleft=pos)
        self.callback = callback


    # Define function for normal button state
    def normal(self):
        self.image = normal
        pygame.mouse.set_cursor()

    # Define function for mouse hover state
    def hover(self):
        self.image = hover
        pygame.mouse.set_cursor(hand)

    # Define function for pressed state
    def pressed(self):
        self.image = pressed


# Set a variabe to True and enter loop
running = True
while running:

    # Fill screen with background color
    screen.fill(screen_bg)

    # Start event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Create a button from the Button class with args for state, position, and callback
    button = Button(normal, (100, 100), None)

    # Get mouse button from pygame
    left, middle, right = pygame.mouse.get_pressed()

    # If cursor is over button change state to hover else state is normal
    if button.rect.collidepoint(pygame.mouse.get_pos()):
        button.hover()

        # If left mouse button pressed change state to pressed else hover
        if left and button.rect.collidepoint(pygame.mouse.get_pos()):
            button.pressed()
        else:
            button.hover()
    else:
        button.normal()

    # Blit button to screen
    screen.blit(button.image, button.rect)

    # Set framerate and update
    framerate.tick(fps)
    pygame.display.update()
thanks alot! really helped give me a good idea, although i didn't use anyof it, thanks anyway