Aug-28-2022, 02:44 PM
I've been playing around a bit with pygame and image buttons. When creating a button with the button class, I can't seem to get button text correct. It stacks on top of one another in all buttons. Each time I call the class should it not be a new instance of that class? Therefor should not the text be unique to that class. What am I missing here? Thanks for any incite.
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, text='Default Text'): ''' 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.text = text self.callback = callback self.default() def default(self): font = pygame.font.SysFont('verdana', 16) self.text_surf = font.render(self.text, True, 'cyan') self.text_rect = self.text_surf.get_rect() # self.text_rect.center = self.rect.center self.text_rect.center = (65,20) self.image.blit(self.text_surf, self.text_rect.center) btns = [] col = 100 for i in range(3): btns.append(Button(normal, (col, 200), None, text=f'Button {i}')) col += 200 # 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 # Get mouse button from pygame left, middle, right = pygame.mouse.get_pressed() # Blit button to screen for btn in btns: screen.blit(btn.image, btn.rect) # Set framerate and update framerate.tick(fps) pygame.display.update()