Any button starts as an ordinary element.
button = pygameui.Element((250, 250), content="Click me!")
Every type of general element can actually act as a button, but before we do that to our we need to do some preperations.
Start by creating a list called clickable_elements:
clickable_elements = []
Then add the button to the list:
clickable_elements.append(button)
Now we can use this function check if the button has been clicked:
if button.was_clicked(clickable_elements):
print("Button was clicked!")
Final code:
import pygame, sys
import pygameui
pygame.init()
win = pygame.display.set_mode((500, 500))
# List of clickable elements
clickable_elements = []
# Create a button
button = pygameui.Element((250, 250), content="Click me!")
clickable_elements.append(button)
clock = pygame.time.Clock()
while True:
win.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Check if the button was clicked
if button.was_clicked(clickable_elements):
print("Button was clicked!")
# Draw the button
button.draw(win)
pygame.display.flip()
clock.tick(60)
Result:
Now you have a button that can be clicked!
There are also other functions that can be used to check if the button is being held down or if the mouse cursor is hovering the button:
Function | Explanation | Arguments |
---|---|---|
is_clicked() | Returnes True if button is currently being held down. | List of clickable elements |
was_clicked() | Returnes True if button was clicked. | List of clickable elements |
is_hovered() | Returnes True if the mouse cursor if hovering the button. | None |