Skip to main content
The 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

Box(surface, rect, bgcolor, border_width=0, border_color=Color('black'))

Parameters

surface
pygame.Surface
required
The pygame surface to which the widget will draw itself
rect
pygame.Rect
required
The outer rectangle defining the location and size of the box on the surface
bgcolor
pygame.Color
required
The background color of the box
border_width
int
default:"0"
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)
border_color
pygame.Color
default:"Color('black')"
Color of the border

Methods

draw()

Renders the box to the surface. Draws the border first, then the background.
box.draw()

get_internal_rect()

Returns the internal rectangle of the box (the area inside the border).
internal_rect = box.get_internal_rect()

Usage Example

The Box widget is commonly used as a base for other widgets. For example, the MessageBoard widget uses Box internally:
widgets.py
class MessageBoard(object):
    def __init__(self, 
            surface,
            rect,
            text,
            padding,
            font=('arial', 20),
            font_color=Color('white'),
            bgcolor=Color('gray25'),
            border_width=0,
            border_color=Color('black')):
        # ...
        self.box = Box(surface, rect, bgcolor, border_width, border_color)
        
    def draw(self):
        # Draw the surrounding box
        self.box.draw()
        # ... draw text on top

Implementation Details

The Box widget calculates the internal rect by subtracting the border width from all sides:
widgets.py
# Internal rectangle
self.in_rect = Rect(
    self.rect.left + self.border_width,
    self.rect.top + self.border_width,
    self.rect.width - self.border_width * 2,
    self.rect.height - self.border_width * 2)
The 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
def draw(self):
    pygame.draw.rect(self.surface, self.border_color, self.rect)        
    pygame.draw.rect(self.surface, self.bgcolor, self.in_rect)
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.

Build docs developers (and LLMs) love