Python Forum
Pygame - Images As Buttons - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Game Development (https://python-forum.io/forum-11.html)
+--- Thread: Pygame - Images As Buttons (/thread-25114.html)



Pygame - Images As Buttons - vman44 - Mar-20-2020

Hi,

I've been trying to develop a game w/ Pygame.

One of the items in my game is a "Goodbye" button.
This is a png file.

The Goodbye image will be placed at a certain location.
Let's call it (x1, y1).

How do I make it into a button which will call "quit()"
if the user clicks on the goodbye image/button?

Thanks.


RE: Pygame - Images As Buttons - michael1789 - Mar-20-2020

There is a tutorial on the forum here.

Do you work with classes? They are the answer to 7/10th of pygame questions.


RE: Pygame - Images As Buttons - Windspar - Mar-20-2020

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
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)



RE: Pygame - Images As Buttons - vman44 - Mar-20-2020

Thanks.

I'll check it out.