Button widget provides interactive buttons with image-based rendering and support for different button types including close buttons, toggle buttons, and action buttons.
Constructor
Parameters
The pygame surface to which the button will draw itself
The position of the button on the surface
The type of button:
"Close", "Toggle", or "Action"List of image file paths. For Toggle buttons, provide two images for the two states
Text label to display on the button
RGB color tuple for the text
Which image state (0 or 1) should show the text overlay for toggle buttons
Padding around the button (currently unused in implementation)
Reference to another widget this button controls (like a MessageBoard to close)
Button Types
Close Button
A simple button that changes state when clicked, typically used to close panels.game.py
Toggle Button
Switches between two states/images when clicked, with optional text overlay.game.py
Action Button
Triggers an action when clicked (like starting an animation).Properties
state
The current state of the button:Button.UNCLICKED(0)Button.CLICKED(1)
toggle
For toggle buttons, indicates which image (0 or 1) is currently displayed.rect
The pygame.Rect representing the button’s bounding box, used for click detection.Methods
draw()
Renders the button to the surface based on its type and current state.widgets.py
mouse_click_event(pos)
Handles mouse click events at the given position.The (x, y) position of the mouse click
Event Handling
Buttons must be registered in the game’s event loop to respond to clicks:game.py
Click Detection
The button uses an internal_point_is_inside() method to determine if a click occurred within its bounds:
widgets.py
Toggle Button Behavior
When a toggle button is clicked, it:- Flips its state
- Switches to the other image
- Recalculates its rect and text position based on the new image size
widgets.py
Button images are loaded with
convert_alpha() to support transparency.Related Widgets
- Text Entry - Another interactive widget for user input
- Images - For non-interactive image display