Box widget provides a simple rectangular container with a background color and optional border. It includes the concept of an “internal rect” - the area inside the border.
Constructor
Parameters
The pygame surface to which the widget will draw itself
The outer rectangle defining the location and size of the box on the surface
The background color of the box
Width of the border. If 0, no border is drawn. If > 0, the border is drawn inside the bounding rect of the widget (so take this into account when computing internal space of the box)
Color of the border
Methods
draw()
Renders the box to the surface. Draws the border first, then the background.get_internal_rect()
Returns the internal rectangle of the box (the area inside the border).Usage Example
The Box widget is commonly used as a base for other widgets. For example, the MessageBoard widget uses Box internally:widgets.py
Implementation Details
The Box widget calculates the internal rect by subtracting the border width from all sides:widgets.py
draw() method renders the border first (filling the entire rect), then draws the background color over it, leaving only the border visible around the edges:
widgets.py
The border is drawn inside the bounding rect, not outside. This means a box with
width=100 and border_width=5 will have an internal width of only 90 pixels.Related Widgets
- MessageBoard - Uses Box as a base for text display
- Moving Objects - MovingRect draws colored rectangles without using Box