Mar-20-2020, 01:03 PM
You should learn to break it down to parts.
1. You need a surface.
2. You need a position.
3. You need a callback
4. You need event action function.
Now you need a structure to hold data. There many ways to build it and store. Here two ways. Dict and a class. I would recommend the class. But do what you like.
Dict example
1. You need a surface.
2. You need a position.
3. You need a callback
4. You need event action function.
Now you need a structure to hold data. There many ways to build it and store. Here two ways. Dict and a class. I would recommend the class. But do what you like.
Dict example
def create_button(button, image, position, callback): button["image"] = image button["rect"] = image.get_rect(topleft=position) button["callback"] = callback def button_on_click(button, event): if event.button == 1: if button["rect"].collidepoint(event.pos): button["callback"](button) def push_button_goodbye(button): print("You push Goodbye button") # Define your button button = {} # Create button create_button(button, your_image, (10, 10), push_button_goodbye) # In event loop see if button is trigger. Under pygame.MOUSEBUTTONDOWN. button_on_click(button, event) # In main loop draw area. surface.blit(button["image"], button["rect"])Class example
class Button: def __init__(self, image, position, callback): self.image = image self.rect = image.get_rect(topleft=position) self.callback = callback def on_click(self, event): if event.button == 1: if self.rect.collidepoint(event.pos): self.callback(self) # Define and create button button = Button(your_image, (10, 10), push_button_goodbye) # In event loop. Under pygame.MOUSEBUTTONDOWN. button.on_click(event) # In main loop draw area. surface.blit(button.image, button.rect)
99 percent of computer problems exists between chair and keyboard.