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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
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() |
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