Overview
TheButton class creates a rectangular, clickable button widget. It supports multiple button types including “Close”, “Toggle”, and “Action” buttons, each with different behaviors.
Constructor
Parameters
The pygame surface to which the button will draw itself.
The position of the button on the surface.
The type of button. Options: “Close”, “Toggle”, “Action”.
List of image file paths for the button states. For Toggle buttons, provide two images.
Text label to display on the button.
RGB color tuple for the text label.
Index of the image to show the text overlay on (for Toggle buttons).
Padding around the button content.
Reference to an attached widget (e.g., a MessageBoard that the button controls).
State Constants
Methods
draw()
Draws the button to the surface with the appropriate image and text based on button type and state.- Close buttons: Always draw the first image
- Toggle buttons: Draw the image corresponding to the current toggle state, and overlay text if
toggle == textimg
mouse_click_event(pos)
Handles mouse click events for the button.The (x, y) position of the mouse click.
- Close: Sets state to
CLICKEDif click is inside the button - Toggle: Toggles state and switches to the alternate image
- Action: Triggers an action (starts an animation in the implementation)
_point_is_inside(mpos)
Internal method to check if a point is inside the button’s boundaries.The position to check.
True if the point is inside the button, False otherwise.
Attributes
state- Current button state (UNCLICKED or CLICKED)toggle- Current toggle state (0 or 1) for Toggle buttonsrect- The pygame.Rect defining the button’s boundaries
Usage Examples
Close Button
Fromgame.py:
Toggle Button
Fromgame.py:
Notes
- Button images are loaded with
convert_alpha()for transparency support - Text is rendered using “Times New Roman” font at size 25
- Text is automatically centered on the button
- Toggle buttons alternate between two images when clicked
- The button automatically recalculates dimensions when toggling