Aug-28-2022, 01:26 AM
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.
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()
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags
Download my project scripts
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags
Download my project scripts