Package organization

The pygame_menu.widgets package contains the widget support for the Menu. Its structure consists of several sub-packages:

pygame_menu/
    widgets/
        core/           Main object classes for Widget and Selector
        selection/      Selection effect applied to widgets
        widget/         Menu widget objects

Create a widget

All widget classes shall inherit from pygame_menu.widgets.core.widget.Widget, and they must be located in the pygame_menu.widgets.widget package. The most basic widget should contain this code:

from pygame_menu.widgets.core.widget import Widget
from pygame_menu._types import EventVectorType

class MyWidget(Widget):

    def __init__(self, params):
        super(MyWidget, self).__init__(params)
        ...

    def _apply_font(self) -> None:
        """
        Function triggered after a font is applied to the widget
        by Menu._configure_widget() method.
        """
        ...

    def _draw(self, surface: 'pygame.Surface') -> None:
        """
        Draw the widget on a given surface.
        This method must be overridden by all classes.
        """
        # Draw the self._surface pygame object on the given surface
        surface.blit(self._surface, self._rect.topleft)

    def _render(self) -> Optional[bool]:
        """
        Render the Widget surface.

        This method shall update the attribute ``_surface`` with a :py:class:`pygame.Surface`
        object representing the outer borders of the widget.

        .. note::

            Before rendering, check out if the widget font/title/values are
            set. If not, it is probable that a zero-size surface is set.

        .. note::

            Render methods should call
            :py:meth:`pygame_menu.widgets.core.widget.Widget.force_menu_surface_update`
            to force Menu to update the drawing surface.

        :return: ``True`` if widget has rendered a new state, ``None`` if the widget has not changed, so render used a cache
        """
        ...

        # Generate widget surface
        self._surface = pygame.surface....

        # Update the width and height of the Widget
        self._rect.width, self._rect.height = self._surface.get_size() + SomeConstants

        # Force menu to update its surface on next Menu.render() call
        self.force_menu_surface_update()

    def update(self, events: EventVectorType) -> bool:
        """
        Update according to the given events list and fire the callbacks. This
        method must return ``True`` if it updated (the internal variables
        changed during user input).

        .. note::

            Update is not performed if the Widget is in ``readonly`` state or
            it's hidden. However, ``apply_update_callbacks`` method is called
            in most widgets, except :py:class:`pygame_menu.widgets.NoneWidget`.

        :param events: List/Tuple of pygame events
        :return: ``True`` if updated
        """
        ...
        return False

Warning

After creating the widget, it must be added to the __init__.py file of the

pygame_menu.widgets package.

from pygame_menu.widgets.widget.mywidget import MyWidget

To add the widget to the pygame_menu.menu.Menu class, a public method add_mywidget() must be added to the pygame_menu._widgetmanager.WidgetManager class with the following structure. Or pygame_menu._widgetmanager.WidgetManager.generic_widget() can be used.

import pygame_menu.widgets

class WidgetManager(object):
    ...

    def mywidget(self, params, **kwargs):
        """
        Add MyWidget to the menu.
        """
        attributes = self._filter_widget_attributes(kwargs)

        # Create your widget
        widget = pygame_menu.widgets.MyWidget(..., **kwargs)

        self._configure_widget(widget=widget, **attributes)
        widget.set_default_value(default) # May add the default value
        self._append_widget(widget)

        return widget

    ...

Note

This method uses the kwargs parameter for defining the settings of the Widget, such as the background, margin, etc. This is applied automatically by the Menu widget addition class (WidgetManager). If MyWidget needs additional parameters, please use some that are not named as the default kwargs used by the Menu Widget system.

The function must return the created widget object.

Note

The widget _render method should always call pygame_menu.widgets.core.widget.Widget.force_menu_surface_update() method, this ensures that Menu updates the surface and the positioning.

Note

From v4 menu introduced a cache state for the draw surface. This cache is updated if any widget update its status (update() returned True) or the surface was rendered. Anyway, execution-time elements that changes over time (outside _render) should force cache rendering (for example the blinking cursor of text). If your widget has any property like this, the method pygame_menu.widgets.core.widget.Widget.force_menu_surface_cache_update() must be called within your Widget.

Create a selection effect

The widgets in Menu are drawn with the following idea:

  1. Each time a new Widget is added, regenerate their position.

  2. Widgets can either be active or inactive. The active widget will catch user events as keyboard or mouse.

  3. Active widgets have a decoration, named Selection

  4. The drawing process is:

    1. Draw Menu background color/image

    2. Draw all widgets

    3. Draw Selection decoration on selected widget surface area

    4. Draw menubar

    5. Draw scrollbar

For defining a new selection effect, a new pygame_menu.widgets.core.Selection subclass must be added to the pygame_menu.widgets.selection package. A basic class must contain the following code:

from pygame_menu.widgets.core.selection import Selection

class MySelection(Selection):

    def __init__(self):
        # Call the constructor of the Selection providing the left, right, top and bottom margins
        # of your Selection effect box.
        #
        #  --------------------------
        # |          ^ top           |  In this example, XXXX represents the
        # | left  XXXXXXXXXXXX right |  Widget to be Selected.
        # |<----> XXXXXXXXXXXX<----->|  left, right, top and bottom must be described
        # |         v bottom         |  in pixels
        #  --------------------------
        #
        super(MySelection, self).__init__(margin_left, margin_right, margin_top, margin_bottom)
        self.your_params = ...

    def draw(self, surface, widget):
        """
        This method receives the surface to draw the selection and the
        widget itself. For retrieving the Selection coordinates the rect
        object from widget should be used.
        """
        surface.draw(.....)

Warning

After creating the selection effect, it must be added to __init__.py file of the pygame_menu.widgets package.

from pygame_menu.widgets.selection.myselection import MySelection

Finally, this new selection effect can be set by following one of these two instructions:

  1. Pass it when adding a new widget to the menu

    import pygame_menu
    
    menu = pygame_menu.Menu(...)
    menu.add.button(..., selection_effect=pygame_menu.widgets.MySelection(...))
    
  2. To apply it on all menus and widgets (and avoid passing it for each added widget), a theme can be created

    import pygame_menu
    
    MY_THEME = pygame_menu.themes.Theme(
        ...,
        widget_selection_effect=pygame_menu.widgets.MySelection(...)
    )
    
    menu = pygame_menu.Menu(..., theme=MY_THEME)
    

Decorate a Menu / Widgets

All menu objects can be decorated with polygons (lines, circles, rectangles, paths), images, text, or callable functions. The decorations can be drawn before the source object (prev) or after the object (post) depending of the object type.

To add a decoration, you must access the decorator class from the object (Menu, ScrollArea, any Widget) using get_decorator() method. And use the Decorator class API to add decorations to your object.

Note

Decorations don’t change the width/height of the object. These are visual/only. If applied on a widget, use padding to enlarge the widget rect if you need such feature.

Note

For all decoration, the (0, 0) coordinate belongs to the center of the object.

decorator = my_widget.get_decorator()
decorator.add_polygon([(1, 1), (1, 10), (10, 1)], color=(255, 0, 0))

# If the widget needs a bigger margin
my_widget.set_padding((25, 25, 10, 10))

decorator = menu.get_decorator()
decorator.add_line((10, 10), (100, 100), color=(45, 180, 34), width=10)

Decorator API

class pygame_menu._decorator.Decorator(obj, decorator_id='', verbose=True)[source]

Decorator class.

Parameters:
  • obj (Union[Widget, ScrollArea, Menu]) – Object to decorate

  • decorator_id (str) – ID of the decorator

  • verbose (bool) – Enable/disable verbose mode (warnings/errors)

add_arc(x, y, radius, init_angle, final_angle, color, width=0, prev=True, gfx=True, **kwargs)[source]

Adds an arc.

kwargs (Optional)
  • use_center_positioning (bool) – Uses object center position as (0, 0). True by default

Parameters:
  • x (Union[int, float]) – X position in px, being 0 the center of the object

  • y (Union[int, float]) – Y position in px, being 0 the center of the object

  • radius (Union[int, float]) – Circle radius in px

  • init_angle (Union[int, float]) – Initial angle in degrees, from 0 to 360

  • final_angle (Union[int, float]) – Final angle in degrees, from 0 to 360

  • color (Union[Tuple[int, int, int], Tuple[int, int, int, int], str, int, Color]) – Color of the polygon

  • width (int) – Line border width. Only valid if filled=False

  • prev (bool) – If True draw previous the object, else draws post

  • gfx (bool) – If True uses pygame gfxdraw instead of draw

  • kwargs – Optional keyword arguments

Return type:

str

Returns:

ID of the decoration

add_baseimage(x, y, image, prev=True, centered=False, **kwargs)[source]

Adds a pygame_menu.baseimage.BaseImage object.

Note

If your pygame_menu.baseimage.BaseImage object changes over time set decorator.cache=False or force cache manually by calling pygame_menu._decorator.Decorator.force_cache_update().

kwargs (Optional)
  • use_center_positioning (bool) – Uses object center position as (0, 0). True by default

Parameters:
  • x (Union[int, float]) – X position in px, being 0 the center of the object

  • y (Union[int, float]) – Y position in px, being 0 the center of the object

  • image (BaseImage) – BaseImage object

  • prev (bool) – If True draw previous the object, else draws post

  • centered (bool) – If True the image is centered

  • kwargs – Optional keyword arguments

Return type:

str

Returns:

ID of the decoration

add_bezier(coords, color, steps=5, prev=True, **kwargs)[source]

Adds a Bézier curve.

kwargs (Optional)
  • use_center_positioning (bool) – Uses object center position as (0, 0). True by default

Parameters:
Return type:

str

Returns:

ID of the decoration

add_callable(fun, prev=True, pass_args=True)[source]

Adds a callable method. The function receives the surface and the object; for example, if adding to a widget:

fun(surface, object)

Note

If your callable function changes over time set decorator.cache=False or force cache manually by calling Decorator method pygame_menu._decorator.Decorator.force_cache_update(). Also, the object should force the menu surface cache to update.

Parameters:
  • fun (Union[Callable[[Surface, Any], Any], Callable[[], Any]]) – Function

  • prev (bool) – If True draw previous the object, else draws post

  • pass_args (bool) – If False function is called without (surface, object) as args

Return type:

str

Returns:

ID of the decoration

add_circle(x, y, radius, color, filled, width=0, prev=True, gfx=True, **kwargs)[source]

Adds a circle.

kwargs (Optional)
  • use_center_positioning (bool) – Uses object center position as (0, 0). True by default

Parameters:
  • x (Union[int, float]) – X position in px, being 0 the center of the object

  • y (Union[int, float]) – Y position in px, being 0 the center of the object

  • radius (Union[int, float]) – Circle radius in px

  • color (Union[Tuple[int, int, int], Tuple[int, int, int, int], str, int, Color]) – Color of the polygon

  • filled (bool) – If True fills the polygon with the given color

  • width (int) – Line border width. Only valid if filled=False

  • prev (bool) – If True draw previous the object, else draws post

  • gfx (bool) – If True uses pygame gfxdraw instead of draw

  • kwargs – Optional keyword arguments

Return type:

str

Returns:

ID of the decoration

add_ellipse(x, y, rx, ry, color, filled, prev=True, **kwargs)[source]

Adds an ellipse.

kwargs (Optional)
  • use_center_positioning (bool) – Uses object center position as (0, 0). True by default

Parameters:
  • x (Union[int, float]) – X position in px, being 0 the center of the object

  • y (Union[int, float]) – Y position in px, being 0 the center of the object

  • rx (Union[int, float]) – Horizontal radius of the ellipse

  • ry (Union[int, float]) – Vertical radius of the ellipse

  • color (Union[Tuple[int, int, int], Tuple[int, int, int, int], str, int, Color]) – Color of the polygon

  • filled (bool) – If True fills the polygon with the given color

  • prev (bool) – If True draw previous the object, else draws post

  • kwargs – Optional keyword arguments

Return type:

str

Returns:

ID of the decoration

add_fill(color, prev=True)[source]

Fills the decorator rect object.

kwargs (Optional)
  • use_center_positioning (bool) – Uses object center position as (0, 0). True by default

Parameters:
Return type:

str

Returns:

ID of the decoration

add_hline(x1, x2, y, color, width=1, prev=True, **kwargs)[source]

Adds a horizontal line.

kwargs (Optional)
  • use_center_positioning (bool) – Uses object center position as (0, 0). True by default

Parameters:
Return type:

str

Returns:

ID of the decoration

add_line(pos1, pos2, color, width=1, prev=True, **kwargs)[source]

Adds a line.

kwargs (Optional)
  • use_center_positioning (bool) – Uses object center position as (0, 0). True by default

Parameters:
Return type:

str

Returns:

ID of the decoration

add_pie(x, y, radius, init_angle, final_angle, color, prev=True, **kwargs)[source]

Adds an unfilled pie.

kwargs (Optional)
  • use_center_positioning (bool) – Uses object center position as (0, 0). True by default

Parameters:
  • x (Union[int, float]) – X position in px, being 0 the center of the object

  • y (Union[int, float]) – Y position in px, being 0 the center of the object

  • radius (Union[int, float]) – Circle radius in px

  • init_angle (Union[int, float]) – Initial angle in degrees, from 0 to 360

  • final_angle (Union[int, float]) – Final angle in degrees, from 0 to 360

  • color (Union[Tuple[int, int, int], Tuple[int, int, int, int], str, int, Color]) – Color of the polygon

  • prev (bool) – If True draw previous the object, else draws post

  • kwargs – Optional keyword arguments

Return type:

str

Returns:

ID of the decoration

add_pixel(x, y, color, prev=True, **kwargs)[source]

Adds a pixel.

kwargs (Optional)
  • use_center_positioning (bool) – Uses object center position as (0, 0). True by default

Parameters:
  • x (Union[int, float]) – X position in px, being 0 the center of the object

  • y (Union[int, float]) – Y position in px, being 0 the center of the object

  • color (Union[Tuple[int, int, int], Tuple[int, int, int, int], str, int, Color]) – Color of the pixel

  • prev (bool) – If True draw previous the object, else draws post

  • kwargs – Optional keyword arguments

Return type:

str

Returns:

ID of the decoration

add_polygon(coords, color, filled, width=0, prev=True, gfx=True, **kwargs)[source]

Adds a polygon.

kwargs (Optional)
  • use_center_positioning (bool) – Uses object center position as (0, 0). True by default

Parameters:
Return type:

str

Returns:

ID of the decoration

add_rect(x, y, rect, color, width=0, prev=True, **kwargs)[source]

Adds a BaseImage object.

kwargs (Optional)
  • use_center_positioning (bool) – Uses object center position as (0, 0). True by default

Parameters:
  • x (Union[int, float]) – X position in px, being 0 the center of the object

  • y (Union[int, float]) – Y position in px, being 0 the center of the object

  • rect (Rect) – Rect to draw

  • color (Union[Tuple[int, int, int], Tuple[int, int, int, int], str, int, Color]) – Color of the rect

  • width (int) – Border width of the rect. If 0 draw a filled rectangle

  • prev (bool) – If True draw previous the object, else draws post

  • kwargs – Optional keyword arguments

Return type:

str

Returns:

ID of the decoration

add_rectangle(x, y, width, height, color, border=0, prev=True, **kwargs)[source]

Adds a BaseImage object.

kwargs (Optional)
  • use_center_positioning (bool) – Uses object center position as (0, 0). True by default

Parameters:
  • x (Union[int, float]) – X position in px, being 0 the center of the object

  • y (Union[int, float]) – Y position in px, being 0 the center of the object

  • width (Union[int, float]) – Rectangle width

  • height (Union[int, float]) – Rectangle height

  • color (Union[Tuple[int, int, int], Tuple[int, int, int, int], str, int, Color]) – Color of the rectangle

  • border (int) – Border width of the rectangle. If 0 draw a filled rectangle

  • prev (bool) – If True draw previous the object, else draws post

  • kwargs – Optional keyword arguments

Return type:

str

Returns:

ID of the decoration

add_surface(x, y, surface, prev=True, centered=False, **kwargs)[source]

Adds a surface.

kwargs (Optional)
  • use_center_positioning (bool) – Uses object center position as (0, 0). True by default

Parameters:
  • x (Union[int, float]) – X position in px, being 0 the center of the object

  • y (Union[int, float]) – Y position in px, being 0 the center of the object

  • surface (Surface) – Surface

  • prev (bool) – If True draw previous the object, else draws post

  • centered (bool) – If True the surface is centered

  • kwargs – Optional keyword arguments

Return type:

str

Returns:

ID of the decoration

add_text(x, y, text, font, size, color, prev=True, antialias=True, centered=False, **kwargs)[source]

Adds a text.

kwargs (Optional)
  • use_center_positioning (bool) – Uses object center position as (0, 0). True by default

Parameters:
  • x (Union[int, float]) – X position in px, being 0 the center of the object

  • y (Union[int, float]) – Y position in px, being 0 the center of the object

  • text (str) – Text to draw

  • font (Union[str, Font, Path]) – Font path or pygame object

  • size (int) – Size of the font to render

  • color (Union[Tuple[int, int, int], Tuple[int, int, int, int], str, int, Color]) – Font color

  • prev (bool) – If True draw previous the object, else draws post

  • antialias – Font antialias enabled

  • centered – If True the text is centered

  • kwargs – Optional keyword arguments

Return type:

str

Returns:

ID of the decoration

add_textured_polygon(coords, texture, tx=0, ty=0, prev=True, **kwargs)[source]

Adds a textured polygon.

Note

If your pygame_menu.baseimage.BaseImage object changes over time set decorator.cache=False or force cache manually by calling pygame_menu._decorator.Decorator.force_cache_update.

kwargs (Optional)
  • use_center_positioning (bool) – Uses object center position as (0, 0). True by default

Parameters:
Return type:

str

Returns:

ID of the decoration

add_vline(x, y1, y2, color, width=1, prev=True, **kwargs)[source]

Adds a vertical line.

kwargs (Optional)
  • use_center_positioning (bool) – Uses object center position as (0, 0). True by default

Parameters:
Return type:

str

Returns:

ID of the decoration

disable(decorid)[source]

Disable a certain decoration from ID. Raises IndexError if decoration was not found.

Parameters:

decorid (str) – Decoration ID

Return type:

Decorator

Returns:

Self reference

draw_post(surface)[source]

Draw post.

Parameters:

surface (Surface) – Pygame surface

Return type:

Decorator

Returns:

Self reference

draw_prev(surface)[source]

Draw prev.

Parameters:

surface (Surface) – Pygame surface

Return type:

Decorator

Returns:

Self reference

enable(decorid)[source]

Enable a certain decoration from ID. Raises IndexError if decoration was not found.

Parameters:

decorid (str) – Decoration ID

Return type:

Decorator

Returns:

Self reference

force_cache_update(prev=None)[source]

Forces cache update.

Parameters:

prev (Optional[bool]) – Update the previous or post surface cache. If None forces both caches to update

Return type:

Decorator

Returns:

Self reference

is_enabled(decorid)[source]

Checks if a certain decoration is enabled or not. Raises IndexError if decoration was not found.

Parameters:

decorid (str) – Decoration ID

Return type:

bool

Returns:

True if enabled

remove(decorid)[source]

Remove a decoration from a given ID. Raises IndexError if decoration was not found.

Parameters:

decorid (str) – Decoration ID

Return type:

Decorator

Returns:

Self reference

remove_all(prev=None)[source]

Remove all decorations.

Parameters:

prev (Optional[bool]) – Remove from prev or post. If None both are removed

Return type:

Decorator

Returns:

Self reference