Skip to main content
The widget system provides a collection of GUI components for building interactive interfaces in Pygame. All widgets share common patterns and are designed to be easy to use and extend.

Available Widgets

Box

Rectangular container with optional borders and background colors

MessageBoard

Text display board for showing multi-line messages

Button

Interactive buttons with click events and toggle states

Images

Static or animated image display (like spinners)

Text Entry

Input field for capturing user text

Moving Objects

Animated rectangles, images, and circles with collision detection

Common Patterns

Surface Parameter

Most widgets receive a surface argument in the constructor. This is the pygame surface to which the widget will draw itself when its draw() method is called.
self.screen = pygame.display.set_mode((580, 500), 0, 32)
widget = SomeWidget(self.screen, ...)

Position and Rectangles

Widgets use two main approaches for positioning:
  • pygame.Rect: Used by Box and MessageBoard for defining rectangular areas
  • vec2d: Used by interactive widgets like Button and textEntry for simpler positioning
# Using pygame.Rect
rect = pygame.Rect(120, 120, 125, 30)  # x, y, width, height
widget = MessageBoard(surface, rect=rect, ...)

# Using vec2d
from vec2d import vec2d
pos = vec2d(250, 250)
button = Button(surface, pos=pos, ...)

Colors

Colors can be specified as:
  • pygame.Color objects: pygame.Color('yellow') or pygame.Color(50, 20, 0)
  • RGB tuples: (255, 255, 255)

Drawing Widgets

All widgets implement a draw() method that must be called each frame:
def draw(self):
    self.draw_background()
    
    for obj in self.world:
        obj.draw()
    
    pygame.display.flip()

Widget Lifecycle

  1. Initialization: Create widget with surface and parameters
  2. Event Handling: Process user input (for interactive widgets)
  3. Drawing: Call draw() method each frame to render

Exception Classes

The widget system defines two custom exceptions:

WidgetError

Base exception class for widget-related errors.
class WidgetError(Exception): pass

LayoutError

Raised when widget layout constraints are violated (e.g., text too large for MessageBoard).
class LayoutError(WidgetError): pass
This exception is raised by MessageBoard when text cannot fit within the specified dimensions with padding.
Unless otherwise specified, all rectangles are pygame.Rect instances, and all colors are pygame.Color instances.

Next Steps

Box Widget

Learn about the basic rectangular container

MessageBoard

Display text messages to users

Build docs developers (and LLMs) love