_images/pygame_menu.png

pygame-menu

@ppizarror License MIT Python 2.7+/3.4+ Pygame 1.9+/2.0+ PyPi package Travis Total alerts Language grade: Python Codecov Open issues PyPi downloads

Source repo on GitHub, and run it on Repl.it

Introduction

Pygame-menu is a python-pygame library for creating menus. It supports selectors, buttons, labels, color inputs, and text inputs, with many options to customize.

Comprehensive documentation for the latest version v3+ is available at https://pygame-menu.readthedocs.io

For pygame-menu v2, check out https://github.com/ppizarror/pygame-menu/blob/v2/README.md

Install Instructions

Pygame-menu can be installed via pip. Simply run:

$> pip install pygame-menu

To build the documentation from a Git repository:

$> clone https://github.com/ppizarror/pygame-menu
$> cd pygame-menu
$> pip install -e .[doc]
$> cd docs
$> make html

First steps

Making games using pygame is really cool, but most games (or applications) require end-user configuration. Creating complex GUI objects to display a menu can be painful. That why pygame-menu was designed.

Here is a simple example of how to create a menu with pygame-menu (the code is available in pygame_menu.examples.simple.py):

  1. Import the required libraries
import pygame
import pygame_menu
  1. Initialize pygame
pygame.init()
surface = pygame.display.set_mode((600, 400))
  1. Make your menu
def set_difficulty(value, difficulty):
    # Do the job here !
    pass

def start_the_game():
    # Do the job here !
    pass

menu = pygame_menu.Menu(300, 400, 'Welcome',
                       theme=pygame_menu.themes.THEME_BLUE)

menu.add_text_input('Name :', default='John Doe')
menu.add_selector('Difficulty :', [('Hard', 1), ('Easy', 2)], onchange=set_difficulty)
menu.add_button('Play', start_the_game)
menu.add_button('Quit', pygame_menu.events.EXIT)
  1. Run your menu
menu.mainloop(surface)
_images/first_steps.png

Tadada… !!! Such a beautiful menu \(^o^)/

Interested in going deeper into menu design ?

Creating menus

Ready to go deeper into menu usage?

Configuring the menu

The pygame_menu.Menu is the base class to draw the graphical items on the screen. It offers many parameters to let you adapt the behavior and the visual aspects of the menu.

The less trivial ones are explained here.

Widgets position

By default, the widgets are centered horizontally (widget_alignment=ALIGN_CENTER). All are included in a virtual rectangle positioned at 0 pixel below the title bar and 0 pixel from the left border (widget_offset=(0, 0)).

In the same way, an offset can be defined for the title using the parameter title_offset.

The horizontal alignment can be changed with one of the following values:

Alignment Description
pygame_menu.locals.ALIGN_LEFT Left alignment
pygame_menu.locals.ALIGN_CENTER Center alignment
pygame_menu.locals.ALIGN_RIGHT Right alignment

The content of the menu can be centered vertically after all widgets have been added by calling the method pygame_menu.Menu.center_content():

menu = pygame_menu.Menu(...)

menu.add_text_input(...)
menu.add_selector(...)
menu.add_button(...)
menu.add_button(...)

Note

If the menu size is insufficient to show all of the widgets, horizontal and/or vertical scrollbar(s) will appear automatically.

Column and row

By default, the widgets are arranged in one unique column. But using the columns and rows parameters, it is possible to arrange them in a grid.

The defined grid of columns x rows cells will be completed with the widgets (in order of definition) column by column starting at the top-left corner of the menu.

On-close callback

A callback can be defined using the onclose parameter, it will be called when the menu (end sub-menus) is closing. This parameter can take one of these two types of values:

  • a python callable object (a function, a method, a class, …) that will be called without any arguments.

  • a specific event of pygame_menu. The possible events are the following:

    Event Description
    pygame_menu.events.BACK Go back to the previously opened menu
    pygame_menu.events.DISABLE_CLOSE The menu can not be closed
    pygame_menu.events.EXIT Exit the program (not only the menu)
    pygame_menu.events.RESET Go back to the first opened menu

Display a menu

The First steps chapter shows the way to display the menu, this method lets pygame-menu managing the event loop by calling the pygame_menu.Menu.mainloop() :

def draw_background():
    ...

mymenu = Menu(...)

mymenu.mainloop(surface, bgfun=draw_background)

There is a second way that gives more flexibility to the application because the events loop remains managed outside of the menu. In this case the application is in charge to update and draw the menu when it is necessary.

def draw_background():
    ...

mymenu = Menu(...)

while True:

    draw_background()

    events = pygame.event.get()
    for event in events:
        if event.type == pygame.QUIT:
            exit()

    if mymenu.is_enabled():
        mymenu.update(events)
        mymenu.draw(surface)

    pygame.display.update()
class pygame_menu.Menu(height, width, title, center_content=True, column_force_fit_text=False, column_max_width=None, columns=1, enabled=True, joystick_enabled=True, menu_id='', menu_position=(50, 50), mouse_enabled=True, mouse_motion_selection=False, mouse_visible=True, onclose=None, rows=None, theme=<pygame_menu.themes.Theme object>, **kwargs)[source]

Menu object.

Parameters:
  • height (int, float) – Height of the Menu (px)
  • width (int, float) – Width of the Menu (px)
  • title (str) – Title of the Menu (main title)
  • center_content (bool) – Auto centers the menu on the vertical position after a widget is added/deleted
  • column_force_fit_text (bool) – Force text fitting of widgets if the width exceeds the column max width
  • column_max_width (tuple, None) – List/Tuple representing the max width of each column in px, None equals no limit
  • columns (int) – Number of columns, by default it’s 1
  • enabled (bool) – Menu is enabled by default or not
  • joystick_enabled (bool) – Enable/disable joystick on the Menu
  • menu_id (str) – ID of the Menu
  • menu_position (tuple, list) – Position in x,y axis (%). Default (50, 50), vertically and horizontally centered
  • mouse_enabled (bool) – Enable/disable mouse click inside the Menu
  • mouse_motion_selection (bool) – Select widgets using mouse motion
  • mouse_visible (bool) – Set mouse visible on Menu
  • onclose (callable, None) – Function applied when closing the Menu
  • rows (int, None) – Number of rows of each column, None if there’s only 1 column
  • theme (pygame_menu.themes.Theme) – Menu theme object, if None use the default theme
  • kwargs – Optional keyword parameters
center_content()[source]

Update draw_region_y based on the current widgets, centering the content of the window.

If the height of the widgets is greater than the height of the Menu, the drawing region will start at zero, using all the height for the scrollbar.

Returns:None
clear()[source]

Full reset Menu and clear all widgets.

Returns:None
disable()[source]

Disables the Menu (doesn’t check events and draw on the surface).

Returns:None
draw(surface, clear_surface=False)[source]

Draw the current Menu into the given surface.

Note

This method should not be used along pygame_menu.Menu.get_current()

Parameters:
  • surface (pygame.Surface) – Pygame surface to draw the Menu
  • clear_surface (bool) – Clear surface using theme default color
Returns:

None

enable()[source]

Enables Menu (can check events and draw).

Returns:None
full_reset()[source]

Reset the Menu back to the first opened Menu.

Returns:None
get_current()[source]

Get current active Menu. If the user has not opened any submenu the pointer object must be the same as the base. If not, this will return the opened menu pointer.

Returns:Menu object
Return type:pygame_menu.Menu
get_id()[source]

Returns the ID of the current/base Menu.

Returns:Menu ID
Return type:str
get_index()[source]

Get selected widget from the Menu.

Returns:Selected widget index
Return type:int
get_input_data(recursive=False)[source]

Return input data from a Menu. The results are given as a dict object. The keys are the ID of each element.

With recursive=True: it collect also data inside the all sub-menus.

Parameters:recursive (bool) – Look in Menu and sub-menus
Returns:Input dict e.g.: {‘id1’: value, ‘id2’: value, …}
Return type:dict
get_rect()[source]

Return Menu rect.

Returns:Rect
Return type:pygame.Rect
get_selected_widget()[source]

Return the selected widget on the Menu.

Returns:Widget object
Return type:pygame_menu.widgets.core.widget.Widget
get_title()[source]

Return the title of the Menu.

Returns:Menu title
Return type:str
get_widget(widget_id, recursive=False)[source]

Return a widget by a given ID from the Menu.

With recursive=True: it looks for a widget in the Menu and all sub-menus. Use current for getting from current and base Menu.

None is returned if no widget found.

Parameters:
  • widget_id (str) – Widget ID
  • recursive (bool) – Look in Menu and submenus
Returns:

Widget object

Return type:

pygame_menu.widgets.core.widget.Widget

is_enabled()[source]
Returns:True if the Menu is enabled
Return type:bool
mainloop(surface, bgfun=None, disable_loop=False, fps_limit=30)[source]

Main loop of Menu. In this function, the Menu handle exceptions and draw. The Menu pauses the application and checks pygame events itself. This method returns until the menu is updated (a widget status has changed).

The execution of the mainloop is at the current Menu level.

menu = pygame_menu.Menu(...)

menu.mainloop(surface)

Note

This method should not be used along pygame_menu.Menu.get_current()

Parameters:
  • surface (pygame.Surface) – Pygame surface to draw the Menu
  • bgfun (callable, None) – Background function called on each loop iteration before drawing the Menu
  • disable_loop (bool) – If true run this method for only 1 loop
  • fps_limit (int, float) – Limit frame per second of the loop, if 0 there’s no limit
Returns:

None

remove_widget(widget)[source]

Remove a widget from the Menu.

Parameters:widget (pygame_menu.widgets.core.widget.Widget) – Widget object
Returns:None
reset(total)[source]

Go back in Menu history a certain number of times from the current Menu. This method operates through the current menu pointer.

Note

This method should not be used along pygame_menu.Menu.get_current()

Parameters:total (int) – How many menus to go back
Returns:None
set_relative_position(position_x, position_y)[source]

Set the menu position relative to the window.

  • Menu left position (x) must be between 0 and 100, if 0 the margin is at the left of the window, if 100 the menu is at the right of the window.
  • Menu top position (y) must be between 0 and 100, if 0 the margin is at the top of the window, if 100 the margin is at the bottom of the window.
Parameters:
  • position_x (int, float) – Left position of the window
  • position_y (int, float) – Top position of the window
Returns:

None

set_sound(sound, recursive=False)[source]

Add a sound engine to the Menu. If recursive=True, the sound is applied to all submenus.

The sound is applied only to the base Menu (not the currently displayed, stored in _current pointer).

Parameters:
Returns:

None

toggle()[source]

Switch between enable and disable.

Returns:None
update(events)[source]

Update the status of the Menu using external events. The update event is applied only on the current Menu.

Note

This method should not be used along pygame_menu.Menu.get_current()

Parameters:events (list[pygame.event.Event]) – Pygame events as a list
Returns:True if mainloop must be stopped
Return type:bool

Adding widgets

Add a text

A label is used to display a text. If the text is too large, it can be wrapped in order to fit the menu size.

Example:

_images/widget_label.png
HELP = "Press ESC to enable/disable Menu "\
       "Press ENTER to access a Sub-Menu or use an option "\
       "Press UP/DOWN to move through Menu "\
       "Press LEFT/RIGHT to move through Selectors."

menu = pygame_menu.Menu(...)
menu.add_label(HELP, max_char=-1, font_size=20)
Menu.add_label(title, label_id='', max_char=0, selectable=False, **kwargs)[source]

Add a simple text to the Menu.

kwargs (Optional):
  • align Widget alignment (str)
  • background_color Color of the background (tuple, list, pygame_menu.baseimage.BaseImage)
  • background_inflate Inflate background color if enabled (bool)
  • font_color Widget font color (tuple, list)
  • font_name Widget font (str)
  • font_size Font size of the widget (int)
  • margin (x,y) margin (tuple, list)
  • shadow Shadow is enabled or disabled (bool)
  • shadow_color Text shadow color (tuple, list)
  • shadow_position Text shadow position, see locals for position (str)
  • shadow_offset Text shadow offset (int, float, None)
Parameters:
  • title (str) – Text to be displayed
  • label_id (str) – ID of the label
  • max_char (int) – Split the title in several labels if length exceeds. (0: don’t split, -1: split to menu width)
  • selectable (bool) – Label accepts user selection, if not selectable long paragraphs cannot be scrolled through keyboard
  • kwargs (any) – Optional keywords arguments
Returns:

Widget object or List of widgets if the text overflows

Return type:

pygame_menu.widgets.Label, list[pygame_menu.widgets.Label]

Add an image

An image can be displayed on a menu. The scale parameter represent the scaling ratio of the image width and height. When scale_smooth=True, the rendering is better but it requires more CPU resources.

Example:

_images/widget_image.png
PATH = os.path.join(os.path.dirname(pygame_menu.__file__),
                    'resources', 'images', 'pygame_menu.png')

menu = pygame_menu.Menu(...)

menu.add_image(PATH, angle=10, scale=(0.15, 0.15))
menu.add_image(PATH, angle=-10, scale=(0.15, 0.15), scale_smooth=True)
Menu.add_image(image_path, angle=0, image_id='', scale=(1, 1), scale_smooth=False, selectable=False, **kwargs)[source]

Add a simple image to the Menu.

kwargs (Optional):
  • align Widget alignment (str)
  • background_color Color of the background (tuple, list, pygame_menu.baseimage.BaseImage)
  • background_inflate Inflate background color if enabled (bool)
  • margin (x,y) margin (tuple, list)
  • selection_color Widget selection color (tuple, list)
  • selection_effect Widget selection effect (pygame_menu.widgets.core.Selection)
Parameters:
  • image_path (str) – Path of the image of the widget
  • angle (int, float) – Angle of the image in degrees (clockwise)
  • image_id (str) – ID of the label
  • scale (tuple, list) – Scale of the image (x,y), float or int
  • scale_smooth (bool) – Scale is smoothed
  • selectable (bool) – Image accepts user selection
  • kwargs (any) – Optional keywords arguments
Returns:

Widget object

Return type:

pygame_menu.widgets.Image

Add a button

A button is a text that fire action when the user trigger it. An action is linked to a button by defining the action parameter with one of the three values:

  • an other pygame_menu.Menu, in this case, it will be displayed when the button is triggered.

  • a python callable object (a function, a method, a class, …) that will be called with the given arguments.

  • a specific event of pygame_menu. The possible events are the following:

    Event Description
    pygame_menu.events.BACK Go back to previously opened menu
    pygame_menu.events.CLOSE Close the menu
    pygame_menu.events.EXIT Exit the program (not only the menu)
    pygame_menu.events.RESET Go back to first opened menu

Example:

_images/widget_button.png
def func(name):
    print("Hello world from", name)  # name will be 'foo'

menu = pygame_menu.Menu(...)

about_menu = pygame_menu.Menu(...)

menu.add_button('Exec', func, 'foo',                    # Execute a function
                align=pygame_menu.locals.ALIGN_LEFT)
menu.add_button(about_menu.get_title(), about_menu,     # Open a sub-menu
                shadow=True, shadow_color=(0, 0, 100))
menu.add_button('Exit', pygame_menu.events.EXIT,         # Link to exit action
                align=pygame_menu.locals.ALIGN_RIGHT)
Menu.add_button(title, action, *args, **kwargs)[source]

Adds a button to the Menu.

The arguments and unknown keyword arguments are passed to the action:

action(*args, **kwargs)
kwargs (Optional):
  • align Widget alignment (str)
  • background_color Color of the background (tuple, list, pygame_menu.baseimage.BaseImage)
  • background_inflate Inflate background color if enabled (bool)
  • button_id Widget ID (str)
  • font_color Widget font color (tuple, list)
  • font_name Widget font (str)
  • font_size Font size of the widget (int)
  • margin (x,y) margin (tuple, list)
  • selection_color Widget selection color (tuple, list)
  • selection_effect Widget selection effect (pygame_menu.widgets.core.Selection)
  • shadow Shadow is enabled or disabled (bool)
  • shadow_color Text shadow color (tuple, list)
  • shadow_position Text shadow position, see locals for position (str)
  • shadow_offset Text shadow offset (int, float, None)
Parameters:
  • title (str) – Title of the button
  • action (pygame_menu.Menu, pygame_menu.events.MenuAction, callable, None) – Action of the button, can be a Menu, an event or a function
  • args (any) – Additional arguments used by a function
  • kwargs (any) – Additional keyword arguments
Returns:

Widget object

Return type:

pygame_menu.widgets.Button

Add a choices list

A selector gives the possibility choose a value in a predefined list. An item of a selector is a tuple: the first element is the text displayed, the others are the arguments passed to the callbacks onchange and onreturn.

Example:

_images/widget_selector.png
def change_background_color(value, surface, color):
    name, index = value
    print("Change color to", name)
    if color == (-1, -1, -1):
        # Generate a random color
        color = (randrange(0, 255), randrange(0, 255), randrange(0, 255))
    surface.fill(color)

menu = pygame_menu.Menu(...)

menu.add_selector('Current color',
                  # list of (Text, parameters...)
                  [('Default', surface, (128, 0, 128)),
                   ('Black', surface, (0, 0, 0)),
                   ('Blue', surface, (0, 0, 255)),
                   ('Random', surface, (-1, -1, -1))],
                  onchange=change_background_color)
Menu.add_selector(title, items, default=0, onchange=None, onreturn=None, selector_id='', **kwargs)[source]

Add a selector to the Menu: several items with values and two functions that are executed when changing the selector (left/right) and pressing return button on the selected item.

The values of the selector are like:

values = [('Item1', a, b, c...), ('Item2', d, e, f..)]

The callbacks receive the current text, its index in the list, the associated arguments and all unknown keyword arguments:

onchange((current_text, index), a, b, c..., **kwargs)
onreturn((current_text, index), a, b, c..., **kwargs)
kwargs (Optional):
  • align Widget alignment (str)
  • background_color Color of the background (tuple, list, pygame_menu.baseimage.BaseImage)
  • background_inflate Inflate background color if enabled (bool)
  • font_color Widget font color (tuple, list)
  • font_name Widget font (str)
  • font_size Font size of the widget (int)
  • margin (x,y) margin (tuple, list)
  • selection_color Widget selection color (tuple, list)
  • selection_effect Widget selection effect (pygame_menu.widgets.core.Selection)
  • shadow Shadow is enabled or disabled (bool)
  • shadow_color Text shadow color (tuple, list)
  • shadow_position Text shadow position, see locals for position (str)
  • shadow_offset Text shadow offset (int, float, None)
Parameters:
  • title (str) – Title of the selector
  • items (list) – Elements of the selector [(‘Item1’, var1..), (‘Item2’…)]
  • default (int) – Index of default value to display
  • onchange (callable, None) – Function when changing the selector
  • onreturn (callable, None) – Function when pressing return button
  • selector_id (str) – ID of the selector
  • kwargs (any) – Additional parameters
Returns:

Widget object

Return type:

pygame_menu.widgets.Selector

Add a text entry

A text input permits to enter a string using a keyboard. Restriction on entered characters can be set using input_type, maxchar, maxwidth and valid_chars parameters.

Example:

_images/widget_textinput.png
def check_name(value):
    print('User name:', value)

menu = pygame_menu.Menu(...)

menu.add_text_input('First name: ', default='John', onreturn=check_name)
menu.add_text_input('Last name: ', default='Doe', maxchar=20)
menu.add_text_input('Password: ', input_type=pygame_menu.locals.INPUT_INT, password=True)
Menu.add_text_input(title, default='', copy_paste_enable=True, cursor_selection_enable=True, input_type='__pygame_menu_input_text__', input_underline='', maxchar=0, maxwidth=0, onchange=None, onreturn=None, password=False, tab_size=4, textinput_id='', valid_chars=None, **kwargs)[source]

Add a text input to the Menu: free text area and two functions that execute when changing the text and pressing return button on the element.

The callbacks receive the current value and all unknown keyword arguments:

onchange(current_text, **kwargs)
onreturn(current_text, **kwargs)
kwargs (Optional):
  • align Widget alignment (str)
  • background_color Color of the background (tuple, list, pygame_menu.baseimage.BaseImage)
  • background_inflate Inflate background color if enabled (bool)
  • font_color Widget font color (tuple, list)
  • font_name Widget font (str)
  • font_size Font size of the widget (int)
  • margin (x,y) margin (tuple, list)
  • selection_color Widget selection color (tuple, list)
  • selection_effect Widget selection effect (pygame_menu.widgets.core.Selection)
  • shadow Shadow is enabled or disabled (bool)
  • shadow_color Text shadow color (tuple, list)
  • shadow_position Text shadow position, see locals for position (str)
  • shadow_offset Text shadow offset (int, float, None)
Parameters:
  • title (str) – Title of the text input
  • default (str, int, float) – Default value to display
  • copy_paste_enable (bool) – Enable text copy, paste and cut
  • cursor_selection_enable (bool) – Enable text selection on input
  • input_type (str) – Data type of the input
  • input_underline (str) – Underline character
  • maxchar (int) – Maximum length of string, if 0 there’s no limit
  • maxwidth (int) – Maximum size of the text widget, if 0 there’s no limit
  • onchange (callable, None) – Function when changing the selector
  • onreturn (callable, None) – Function when pressing return button
  • password (bool) – Text input is a password
  • tab_size (int) – Size of tab key
  • textinput_id (str) – ID of the text input
  • valid_chars (list) – List of authorized chars, None if all chars are valid
  • kwargs (any) – Additional keyword-parameters
Returns:

Widget object

Return type:

pygame_menu.widgets.TextInput

Add a color entry

A color input is similar as a text input but with a limited choice of characters to enter a RGB value of HEX decimal one. There is also a area to show the current color. By default the RGB integers separator is a comma (,).

Example:

_images/widget_colorinput.png
def check_color(value):
    print('New color:', value)

menu = pygame_menu.Menu(...)

menu.add_color_input('RGB color 1: ', color_type='rgb', default=(255, 0, 255), onreturn=check_color, font_size=18)
menu.add_color_input('RGB color 2: ', color_type='rgb', input_separator='-', font_size=18)
menu.add_color_input('HEX color 3: ', color_type='hex', default='#ffaa11', font_size=18)
Menu.add_color_input(title, color_type, color_id='', default='', input_separator=', ', input_underline='_', onchange=None, onreturn=None, previsualization_width=3, **kwargs)[source]

Add a color widget with RGB or Hex format to the Menu. Includes a preview box that renders the given color.

The callbacks receive the current value and all unknown keyword arguments:

onchange(current_color, **kwargs)
onreturn(current_color, **kwargs)
kwargs (Optional):
  • align Widget alignment (str)
  • background_color Color of the background (tuple, list, pygame_menu.baseimage.BaseImage)
  • background_inflate Inflate background color if enabled (bool)
  • font_color Widget font color (tuple, list)
  • font_name Widget font (str)
  • font_size Font size of the widget (int)
  • margin (x,y) margin (tuple, list)
  • selection_color Widget selection color (tuple, list)
  • selection_effect Widget selection effect (pygame_menu.widgets.core.Selection)
  • shadow Shadow is enabled or disabled (bool)
  • shadow_color Text shadow color (tuple, list)
  • shadow_position Text shadow position, see locals for position (str)
  • shadow_offset Text shadow offset (int, float, None)
Parameters:
  • title (str) – Title of the color input
  • color_type (str) – Type of the color input, can be “rgb” or “hex”
  • color_id (str) – ID of the color input
  • default (str, tuple) – Default value to display, if RGB must be a tuple (r,g,b), if HEX must be a string “#XXXXXX”
  • input_separator (str) – Divisor between RGB channels, not valid in HEX format
  • input_underline (str) – Underline character
  • onchange (callable, None) – Function when changing the selector
  • onreturn (callable, None) – Function when pressing return button
  • previsualization_width (int, float) – Previsualization width as a factor of the height
  • kwargs (any) – Additional keyword-parameters
Returns:

Widget object

Return type:

pygame_menu.widgets.ColorInput

Add a vertical spacer

A vertical spacer can be added between two widgets to have a better visual rendering of the menu.

Example:

_images/widget_vmargin.png
menu = pygame_menu.Menu(...)

menu.add_label('Text #1')
menu.add_vertical_margin(100)
menu.add_label('Text #2')
Menu.add_vertical_margin(margin)[source]

Adds a vertical margin to the current Menu.

Parameters:margin (int, float) – Margin in px
Returns:Widget object
Return type:pygame_menu.widgets.VMargin

Adding sounds

A sound engine can be created using the Sound class. The sound engine can be customized by setting a sound file to several sounds defined by a type.

For example, buttons or keys…

Example:

import pygame_menu
from pygame_menu import sound

engine = sound.Sound()
engine.set_sound(sound.SOUND_TYPE_CLICK_MOUSE, '/home/me/click.ogg')
engine.set_sound(sound.SOUND_TYPE_OPEN_MENU, '/home/me/open.ogg')

menu = pygame_menu.Menu(...)
menu.set_sound(engine, recursive=True)  # Apply on menu and all sub-menus

Sound types are the following:

Type Description
pygame_menu.sound.SOUND_TYPE_CLICK_MOUSE Mouse click
pygame_menu.sound.SOUND_TYPE_CLOSE_MENU A menu is closed
pygame_menu.sound.SOUND_TYPE_ERROR Generic error
pygame_menu.sound.SOUND_TYPE_EVENT Generic event
pygame_menu.sound.SOUND_TYPE_EVENT_ERROR Error generated by user
pygame_menu.sound.SOUND_TYPE_KEY_ADDITION User type a key
pygame_menu.sound.SOUND_TYPE_KEY_DELETION User deletes with a key
pygame_menu.sound.SOUND_TYPE_OPEN_MENU A menu is opened
pygame_menu.sound.SOUND_TYPE_WIDGET_SELECTION A widget is selected
class pygame_menu.sound.Sound(uniquechannel=True, frequency=22050, size=-16, channels=2, buffer=4096, devicename='', allowedchanges=5, force_init=False)[source]

Sound engine class.

Parameters:
  • uniquechannel (bool) – Force the channel to be unique, this is set at the moment of creation of the object
  • frequency (int) – Frequency of sounds
  • size (int) – Size of sample
  • channels (int) – Number of channels by default
  • buffer (int) – Buffer size
  • devicename (str) – Device name
  • allowedchanges (bool) – Convert the samples at runtime, only in pygame>=2.0.0
  • force_init (bool) – Force mixer init with new parameters
get_channel()[source]

Return the channel of the sound engine.

Returns:Channel
Return type:pygame.mixer.Channel
get_channel_info()[source]

Return the current channel information of the sound engine.

Returns:An info dict e.g.: {‘busy’: 0, ‘endevent’: 0, ‘queue’: None, ‘sound’: None, ‘volume’: 1.0}
Return type:dict
load_example_sounds(volume=0.5)[source]

Load the example sounds provided by the package.

Parameters:volume (float) – Volume of the sound, (0-1)
Returns:None
pause()[source]

Pause the current channel.

Returns:None
play_click_mouse()[source]

Play click mouse sound.

Returns:None
play_close_menu()[source]

Play close menu sound.

Returns:None
play_error()[source]

Play error sound.

Returns:None
play_event()[source]

Play event sound.

Returns:None
play_event_error()[source]

Play event error sound.

Returns:None
play_key_add()[source]

Play key addition sound.

Returns:None
play_key_del()[source]

Play key deletion sound.

Returns:None
play_open_menu()[source]

Play open menu sound.

Returns:None
play_widget_selection()[source]

Play widget selection sound.

Returns:None
set_sound(sound_type, sound_file, volume=0.5, loops=0, maxtime=0, fade_ms=0)[source]

Link a sound file to a sound type.

Parameters:
  • sound_type (str) – Sound type
  • sound_file (str, None) – Sound file
  • volume (float) – Volume of the sound, from 0.0 to 1.0
  • loops (int) – Loops of the sound
  • maxtime (int, float) – Max playing time of the sound
  • fade_ms (int, float) – Fading ms
Returns:

The status of the sound load, True if the sound was loaded

Return type:

bool

stop()[source]

Stop the current the channel.

Returns:None
unpause()[source]

Unpause channel.

Returns:None

Creating themes

pygame-menu offers many parameters to control the visual aspect of the menu. For an easier usage, all of them are gathered in a specific object called a theme. It is used to customize the menu window itself and all its widgets.

menu = pygame_menu.Menu(300, 400,
                       theme=pygame_menu.themes.THEME_BLUE,
                       title='Welcome')

Note

The theme parameters can be overwritten locally when adding a widget to the menu. See the overwritable ones in the add_… methods

Default themes

Several predefined themes are proposed by pygame-menu.

Theme name Example
pygame_menu.themes.THEME_DEFAULT _images/theme_default.png
pygame_menu.themes.THEME_BLUE _images/theme_blue.png
pygame_menu.themes.THEME_DARK _images/theme_dark.png
pygame_menu.themes.THEME_GREEN _images/theme_green.png
pygame_menu.themes.THEME_ORANGE _images/theme_orange.png
pygame_menu.themes.THEME_SOLARIZED _images/theme_solarized.png

Create a theme

If none of the proposed theme fit to the needs, the Theme give the opportunity to create custom themes.

mytheme = Theme(background_color=(0, 0, 0, 0), # transparent background
                title_shadow=True,
                title_background_color=(4, 47, 126),
                ...)

menu = Menu(..., theme=mytheme)

Of course it is also possible to start from a predefined theme by copying it first.

mytheme = pygame_menu.themes.THEME_ORANGE.copy()
mytheme.title_background_color=(0, 0, 0)

menu = Menu(..., theme=mytheme)

Background Color/Images

Theme background can be both a color or an image. All colors can be defined using a tuple or an list of 3 or 4 numbers between 0 and 255. The format of numers are:

color_opaque = (R,G,B)
color_transparent = (R,G,B,A)

A alpha channels goes from 0 to 255. 0 is transparent, 255 is opaque. For using images as a background color, class pygame_menu.baseimage.BaseImage must be used.

Images needs a Path (file location on disk), a drawing mode, and an optional offset.

myimage = pygame_menu.baseimage.BaseImage(
    image_path=pygame_menu.baseimage.IMAGE_EXAMPLE_GRAY_LINES,
    drawing_mode=pygame_menu.baseimage.IMAGE_MODE_REPEAT_XY,
    offset=(0,0)
)
mytheme.background_color = myimage
Image drawing modes Description
pygame_menu.baseimage.IMAGE_MODE_CENTER Centers the image in the surface
pygame_menu.baseimage.IMAGE_MODE_FILL Fill the image on the surface
pygame_menu.baseimage.IMAGE_MODE_REPEAT_X Repeat the image on x axis
pygame_menu.baseimage.IMAGE_MODE_REPEAT_XY Repeat the image on x and y axis
pygame_menu.baseimage.IMAGE_MODE_REPEAT_Y Repeat the image on y axis
pygame_menu.baseimage.IMAGE_MODE_SIMPLE Write the image on top-left location

Currently, Theme class only supports images for background_color and widget_background_color. Also, only IMAGE_MODE_FILL drawing mode is valid for widget_background_color.

Widget selection effect

A selection effect is a drawing class used to define the way to highlight the focused widget. An instance of the selection effect class is defined in the Theme.widget_selection_effect parameter of a theme. See example on how to add a selection effect in Create a selection effect chapter.

The available selection effects are:

Class Selection effect
pygame_menu.widgets.HighlightSelection Rectangular highlight
pygame_menu.widgets.LeftArrowSelection Left arrow on the widget
pygame_menu.widgets.NoneSelection No selection
pygame_menu.widgets.RightArrowSelection Right arrow on the widget

The selection color is defined in Theme.widget_selection_color.

Fonts

This library also has some fonts to use. To load a font, run this code:

import pygame_menu

font = pygame_menu.font.FONT_NAME
my_theme = Theme(widget_font=font, ...)
Available fonts Preview
pygame_menu.font.FONT_8BIT _images/font_8bit.png
pygame_menu.font.FONT_BEBAS _images/font_bebas.png
pygame_menu.font.FONT_COMIC_NEUE _images/font_comic_neue.png
pygame_menu.font.FONT_FRANCHISE _images/font_franchise.png
pygame_menu.font.FONT_HELVETICA _images/font_helvetica.png
pygame_menu.font.FONT_MUNRO _images/font_munro.png
pygame_menu.font.FONT_NEVIS _images/font_nevis.png
pygame_menu.font.FONT_OPEN_SANS _images/font_open_sans.png
pygame_menu.font.FONT_OPEN_SANS_BOLD _images/font_open_sans_bold.png
pygame_menu.font.FONT_OPEN_SANS_ITALIC _images/font_open_sans_italic.png
pygame_menu.font.FONT_OPEN_SANS_LIGHT _images/font_open_sans_light.png
pygame_menu.font.FONT_PT_SERIF _images/font_pt_serif.png

System fonts can also be used. The available system fonts can be listed using the following command in a python shell:

import pygame
print(pygame.font.get_fonts())

Theme API

class pygame_menu.themes.Theme(**kwargs)[source]

Class defining the visual rendering of menus and widgets.

Note

All colors must be defined with a tuple of 3 or 4 numbers in the formats:

  • (R,G,B)
  • (R,G,B,A)

Red (R), Green (G) and Blue (B) must be numbers between 0 and 255. A means the alpha channel (opacity), if 0 the color is transparent, 100 means opaque.

Parameters:
  • background_color (tuple, list, pygame_menu.baseimage.BaseImage) – Menu background color
  • cursor_color (tuple, list) – Color of cursor
  • cursor_selection_color (tuple, list) – Selection box color
  • focus_background_color (tuple, list) – Color of the widget focus, this must be a tuple of 4 elements. And must be transparent
  • menubar_close_button (bool) – Draw a back-box button on header to close the menu
  • scrollbar_color (tuple, list) – Scrollbars color
  • scrollbar_shadow (bool) – Indicate if a shadow is drawn on each scrollbar
  • scrollbar_shadow_color (tuple, list) – Color of the shadow
  • scrollbar_shadow_offset (int, float) – Offset of shadow
  • scrollbar_shadow_position (str) – Position of shadow
  • scrollbar_slider_color (tuple, list) – Color of the sliders
  • scrollbar_slider_pad (int, float) – Space between slider and scrollbars borders
  • scrollbar_thick (int, float) – Scrollbars thickness
  • selection_color (tuple, list) – Color of the selector widget
  • surface_clear_color (tuple, list) – Surface clear color before applying background function
  • title_background_color (tuple, list) – Title background color
  • title_bar_style (int) – Style of the title, use menubar widget styles
  • title_font (str, None) – Optional title font, if None use the Menu default font
  • title_font_antialias (bool) – Title font renders with antialiasing
  • title_font_color (tuple, list, None) – Title font color, if None use the widget font color
  • title_font_size (int) – Font size of the title
  • title_offset (tuple, list) – Offset (x-position,y-position) of title (px). Default (0,0)
  • title_shadow (bool) – Enable shadow on title
  • title_shadow_color (tuple, list) – Title shadow color
  • title_shadow_offset (int, float) – Offset of shadow on title
  • title_shadow_position (str) – Position of the shadow on title
  • widget_alignment (str) – Widget default alignment
  • widget_background_color (tuple, list, pygame_menu.baseimage.BaseImage, None) – Background color of a widget
  • widget_font (str) – Widget font path or name
  • widget_font_antialias (bool) – Widget font renders with antialiasing
  • widget_font_background_color_from_menu (bool) – Use menu background color as font background color, True by default in pygame v2
  • widget_font_color (tuple, list) – Color of the font
  • widget_font_size (int) – Font size
  • widget_margin (tuple, list) – Horizontal and vertical margin of each element in Menu (px). Default (0, 10)
  • widget_offset (tuple, list) – X,Y axis offset of widgets inside Menu (px). If value less than 1 use percentage of width/height. Default (0, 0)
  • widget_selection_effect (pygame_menu.widgets.core.Selection) – Widget selection effect object
  • widget_shadow (bool) – Indicate if a shadow is drawn on each widget
  • widget_shadow_color (tuple, list) – Color of the shadow
  • widget_shadow_offset (int, float) – Offset of shadow
  • widget_shadow_position (str) – Position of shadow
copy()[source]

Creates a deep copy of the object.

Returns:Copied theme
Return type:Theme
set_background_color_opacity(opacity)[source]

Modify menu background color with given opacity.

Parameters:opacity (int) – Opacity value, from 0 (transparent) to 1 (transparent)
Returns:None
validate()[source]

Validate the values of the theme. If there’s a invalid parameter throws an AssertionError.

This function also converts all lists to tuples. This is done because lists are mutable.

Returns:None

Migration Guide - v2 to v3

  • Removed from library
    • Renamed library pygameMenu to pygame_menu
    • Removed all configuration variables from pygameMenu.config.
    • Removed TextMenu, use Menu and add_label() method instead
  • New Menu behaviour
    • Menu manage the event loop and drawing using Menu.mainloop(surface,bgfun,disable_loop=False,fps_limit=0)
    • User’s application manage the event loop, using Menu.update(events)` and `Menu.draw(surface)
  • Removed from Menu class
  • Renamed Menu method parameters
    • element_name and element from add_button() to title and action
    • values from add_selector() to items
    • widget_id from add_button() to button_id

Advanced usage

This chapter define rules and advanced tips and tricks to develop extensions for pygame-menu. The main addressed topics are:

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
        examples/       Some examples of widgets
        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

class MyWidget(Widget):

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

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

    def draw(self, surface):
        """
        Draw the widget shape.
        """
        # Required, render first, then draw
        self._render()

        # Draw the background of the Widget (optional)
        self._fill_background_color(surface)

        # Draw the self._surface pygame object on the given surface
        surface.blit(self._surface, self._rect.topleft)

    def _render(self):
        """
        Render the widget surface.
        This method shall update the attribute _surface with a pygame.Surface
        representing the outer borders of the widget.
        """
        # 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

    def update(self, events):
        """
        Update internal variable according to the given events list
        and fire the callbacks.
        """
        ...
        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 class, a public method pygame_menu.Menu.add_mywidget() with the following structure has to be added:

import pygame_menu.widgets as _widgets

class Menu(object):
    ...

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

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

        self._configure_widget(widget=widget, **attributes)
        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 in pygame_menu.Menu._configure_widget() method. 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.

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)
    

Widgets API

A menu is in fact a list of widgets arranged on the same surface. Access to a widget in a menu can easily be done with two methods:

widget = menu.get_widget('MyWidgetID')

selected = menu.get_selected_widget()

Each pygame_menu widget and its behaviors are defined in a class. The currently existing classes are:

For advanced programmers, those classes can be used to design custom menus or windows.

Have a look at pygame_menu.widgets.examples.scrollbar.py for instance. It shows how to use the pygame_menu.widgets.ScrollBar class to display large custom surfaces.

Button

class pygame_menu.widgets.Button(title, button_id='', onchange=None, onreturn=None, *args, **kwargs)[source]

Bases: pygame_menu.widgets.core.widget.Widget

Button widget.

Parameters:
  • title (str) – Button title
  • button_id (str) – Button ID
  • onchange (callable, None) – Callback when changing the selector
  • onreturn (callable, None) – Callback when pressing return button
  • args (any) – Optional arguments for callbacks
  • kwargs (any) – Optional keyword-arguments for callbacks
apply(*args)

Run on_return callback when return event. A callback function receives the following arguments:

callback_func( value, *args, *widget._args, **widget._kwargs )
with:
  • value (if something is returned by get_value())
  • args given to this method
  • args of the widget
  • kwargs of the widget
Parameters:args – Extra arguments passed to the callback
Returns:None
change(*args)

Run on_change callback after change event is triggered. A callback function receives the following arguments:

callback_func( value, *args, *widget._args, **widget._kwargs )
with:
  • value (if something is returned by get_value())
  • args given to this method
  • args of the widget
  • kwargs of the widget
Parameters:args – Extra arguments passed to the callback
Returns:None
draw(surface)[source]

Draw the widget shape.

Parameters:surface (pygame.Surface) – Surface to draw
Returns:None
draw_selection(surface)

Draw selection effect on widget.

Parameters:surface (pygame.Surface) – Surface to draw
Returns:None
get_alignment()

Returns widget alignment.

Returns:Widget align, see locals
Return type:str
get_attribute(key, default)

Get attribute value.

Parameters:
  • key (str) – Key of the attribute
  • default (Any) – Value if does not exists
Returns:

Attribute data

Return type:

Any

get_font_info()

Return a dict with the information of the widget font.

Returns:Dict, keys: size (int), name (str), color (tuple), selected_color (tuple), antialias (bool)
Return type:dict
get_id()

Returns the widget ID.

Returns:ID
Return type:str
get_margin()
Returns:Widget margin
Return type:tuple
get_menu()

Return menu reference (if exists).

Returns:Menu reference
Return type:pygame_menu.Menu
get_rect()

Return the Rect object, this forces the widget rendering

Returns:Widget rect
Return type:pygame.Rect
get_selected_time()

Return time the widget has been selected in miliseconds. If the widget is not currently selected, return 0.

Returns:Time in ms
Return type:float
get_selection_effect()
Returns:Selection effect
Return type:pygame_menu.widgets.core.Selection
get_title()

Return the widget title.

Returns:Widget title
Return type:str
get_value()

Return the value. If exception ValueError is raised, no value will be passed to the callbacks.

Returns:Value
Return type:Object
set_alignment(align)

Set the alignment of the widget.

Parameters:align (str) – Widget align, see locals
Returns:None
set_attribute(key, value)

Set widget attribute.

Parameters:
  • key (str) – Key of the attribute
  • value (Any) – Value of the attribute
Returns:

None

set_background_color(color, inflate=(0, 0))

Set widget background color.

Parameters:
Returns:

None

set_controls(joystick=True, mouse=True)

Enable interfaces to control the widget.

Parameters:
  • joystick (bool) – Use joystick
  • mouse (bool) – Use mouse
Returns:

None

set_font(font, font_size, color, selected_color, background_color, antialias=True)

Set the text font.

Parameters:
  • font (str, list) – Name or list of names for font (see pygame.font.match_font for precise format)
  • font_size (int) – Size of font in pixels
  • color (tuple) – Text color
  • selected_color (tuple) – Text color when widget is selected
  • background_color (tuple) – Font background color
  • antialias (bool) – Determines if antialias is applied to font (uses more processing power)
Returns:

None

set_margin(x, y)

Set Widget margin.

Parameters:
Returns:

None

set_max_width(width)

Set widget max width (column support) if force_fit_text is enabled.

Parameters:width (int, float, None) – Width in px, None if max width is disabled
Returns:None
set_menu(menu)

Set menu reference.

Parameters:menu (pygame_menu.Menu) – Menu object
Returns:None
set_position(posx, posy)

Set the position.

Parameters:
Returns:

None

set_selected(selected=True)

Mark the widget as selected.

Parameters:selected (bool) – Set item as selected
Returns:None
set_selection_effect(selection)

Set the selection effect handler.

Parameters:selection (pygame_menu.widgets.core.Selection) – Selection effect class
Returns:None
set_shadow(enabled=True, color=None, position=None, offset=None)

Show text shadow.

Parameters:
  • enabled (bool) – Shadow is enabled or not
  • color (list, None) – Shadow color
  • position (str, None) – Shadow position
  • offset (int, float, None) – Shadow offset
Returns:

None

set_sound(sound)

Set sound engine to the widget.

Parameters:sound (pygame_menu.sound.Sound) – Sound object
Returns:None
set_title(title)

Update the widget title.

Parameters:title (str) – New title
Returns:None
set_value(value)

Set the value.

Warning

This method does not fire the callbacks as it is called programmatically. This behavior is deliberately chosen to avoid infinite loops.

Parameters:value (Object) – Value to be set on the widget
Returns:None
surface_needs_update()

Checks if the widget width/height has changed because events. If so, return true and set the status of the widget (menu widget position needs update) as false. This method is used by .update() from Menu class.

Returns:True if the widget position has changed by events after the rendering.
Return type:bool
update(events)[source]

Update internal variable according to the given events list and fire the callbacks.

Parameters:events (list[pygame.event.Event]) – List of pygame events
Returns:True if updated
Return type:bool
update_callback(func, *args)[source]

Update function triggered by the button. Button cannot point to a Menu, as that is only valid using Menu.add_button() method

Parameters:
  • func (Callable) – Function
  • args – Arguments used by the function once triggered

ColorInput

class pygame_menu.widgets.ColorInput(title='', colorinput_id='', color_type='rgb', input_separator=', ', input_underline='_', cursor_color=(0, 0, 0), onchange=None, onreturn=None, prev_size=3, repeat_keys_initial_ms=450, repeat_keys_interval_ms=80, repeat_mouse_interval_ms=100, *args, **kwargs)[source]

Bases: pygame_menu.widgets.widget.textinput.TextInput

Color input widget.

Parameters:
  • title (str) – Color input title
  • colorinput_id (str) – ID of the text input
  • color_type (str) – Type of color input (rgb, hex)
  • input_separator (str) – Divisor between RGB channels
  • input_underline (str) – Character drawn under each number input
  • cursor_color (tuple) – Color of cursor
  • onchange (callable, None) – Callback when changing the selector
  • onreturn (callable, None) – Callback when pressing return button
  • prev_size (int, float) – Width of the previsualization box in terms of the height of the widget
  • repeat_keys_initial_ms (int, float) – Time in ms before keys are repeated when held
  • repeat_keys_interval_ms (int, float) – Interval between key press repetition when held
  • repeat_mouse_interval_ms (int, float) – Interval between mouse events when held
  • kwargs (any) – Optional keyword-arguments for callbacks
apply(*args)

Run on_return callback when return event. A callback function receives the following arguments:

callback_func( value, *args, *widget._args, **widget._kwargs )
with:
  • value (if something is returned by get_value())
  • args given to this method
  • args of the widget
  • kwargs of the widget
Parameters:args – Extra arguments passed to the callback
Returns:None
change(*args)

Run on_change callback after change event is triggered. A callback function receives the following arguments:

callback_func( value, *args, *widget._args, **widget._kwargs )
with:
  • value (if something is returned by get_value())
  • args given to this method
  • args of the widget
  • kwargs of the widget
Parameters:args – Extra arguments passed to the callback
Returns:None
clear()[source]

Clear the current text.

Returns:None
draw(surface)[source]

Draw the widget shape.

Parameters:surface (pygame.Surface) – Surface to draw
Returns:None
draw_selection(surface)

Draw selection effect on widget.

Parameters:surface (pygame.Surface) – Surface to draw
Returns:None
get_alignment()

Returns widget alignment.

Returns:Widget align, see locals
Return type:str
get_attribute(key, default)

Get attribute value.

Parameters:
  • key (str) – Key of the attribute
  • default (Any) – Value if does not exists
Returns:

Attribute data

Return type:

Any

get_font_info()

Return a dict with the information of the widget font.

Returns:Dict, keys: size (int), name (str), color (tuple), selected_color (tuple), antialias (bool)
Return type:dict
get_id()

Returns the widget ID.

Returns:ID
Return type:str
get_margin()
Returns:Widget margin
Return type:tuple
get_menu()

Return menu reference (if exists).

Returns:Menu reference
Return type:pygame_menu.Menu
get_rect()

Return the Rect object, this forces the widget rendering

Returns:Widget rect
Return type:pygame.Rect
get_selected_time()

Return time the widget has been selected in miliseconds. If the widget is not currently selected, return 0.

Returns:Time in ms
Return type:float
get_selection_effect()
Returns:Selection effect
Return type:pygame_menu.widgets.core.Selection
get_title()

Return the widget title.

Returns:Widget title
Return type:str
get_value()[source]

Return the color value as a tuple or red blue and green channels. If the data is invalid the widget returns (-1,-1,-1).

Returns:Color tuple as (R,G,B)
Return type:tuple
is_valid()[source]

Return true if the current value of the input is a valid color or not.

Returns:True if valid
Return type:bool
set_alignment(align)

Set the alignment of the widget.

Parameters:align (str) – Widget align, see locals
Returns:None
set_attribute(key, value)

Set widget attribute.

Parameters:
  • key (str) – Key of the attribute
  • value (Any) – Value of the attribute
Returns:

None

set_background_color(color, inflate=(0, 0))

Set widget background color.

Parameters:
Returns:

None

set_controls(joystick=True, mouse=True)

Enable interfaces to control the widget.

Parameters:
  • joystick (bool) – Use joystick
  • mouse (bool) – Use mouse
Returns:

None

set_font(font, font_size, color, selected_color, background_color, antialias=True)

Set the text font.

Parameters:
  • font (str, list) – Name or list of names for font (see pygame.font.match_font for precise format)
  • font_size (int) – Size of font in pixels
  • color (tuple) – Text color
  • selected_color (tuple) – Text color when widget is selected
  • background_color (tuple) – Font background color
  • antialias (bool) – Determines if antialias is applied to font (uses more processing power)
Returns:

None

set_margin(x, y)

Set Widget margin.

Parameters:
Returns:

None

set_max_width(width)

Set widget max width (column support) if force_fit_text is enabled.

Parameters:width (int, float, None) – Width in px, None if max width is disabled
Returns:None
set_menu(menu)

Set menu reference.

Parameters:menu (pygame_menu.Menu) – Menu object
Returns:None
set_position(posx, posy)

Set the position.

Parameters:
Returns:

None

set_selected(selected=True)

Mark the widget as selected.

Parameters:selected (bool) – Set item as selected
Returns:None
set_selection_effect(selection)

Set the selection effect handler.

Parameters:selection (pygame_menu.widgets.core.Selection) – Selection effect class
Returns:None
set_shadow(enabled=True, color=None, position=None, offset=None)

Show text shadow.

Parameters:
  • enabled (bool) – Shadow is enabled or not
  • color (list, None) – Shadow color
  • position (str, None) – Shadow position
  • offset (int, float, None) – Shadow offset
Returns:

None

set_sound(sound)

Set sound engine to the widget.

Parameters:sound (pygame_menu.sound.Sound) – Sound object
Returns:None
set_title(title)

Update the widget title.

Parameters:title (str) – New title
Returns:None
set_value(color)[source]

Set the value of the text.

Parameters:text (str, int, float) – New text of the widget
Returns:None
surface_needs_update()

Checks if the widget width/height has changed because events. If so, return true and set the status of the widget (menu widget position needs update) as false. This method is used by .update() from Menu class.

Returns:True if the widget position has changed by events after the rendering.
Return type:bool
update(events)[source]

Update internal variable according to the given events list and fire the callbacks.

Parameters:events (list[pygame.event.Event]) – List of pygame events
Returns:True if updated
Return type:bool

Image

class pygame_menu.widgets.Image(image_path, image_id='', angle=0, scale=(1, 1), scale_smooth=True)[source]

Bases: pygame_menu.widgets.core.widget.Widget

Image widget.

Parameters:
  • image_path (str) – Path of the image
  • image_id (str) – Image ID
  • angle (int, float) – Angle of the image in degrees (clockwise)
  • scale (tuple, list) – Scale of the image (x,y), float or int
  • scale_smooth (bool) – Scale is smoothed
apply(*args)

Run on_return callback when return event. A callback function receives the following arguments:

callback_func( value, *args, *widget._args, **widget._kwargs )
with:
  • value (if something is returned by get_value())
  • args given to this method
  • args of the widget
  • kwargs of the widget
Parameters:args – Extra arguments passed to the callback
Returns:None
change(*args)

Run on_change callback after change event is triggered. A callback function receives the following arguments:

callback_func( value, *args, *widget._args, **widget._kwargs )
with:
  • value (if something is returned by get_value())
  • args given to this method
  • args of the widget
  • kwargs of the widget
Parameters:args – Extra arguments passed to the callback
Returns:None
draw(surface)[source]

Draw the widget shape.

Parameters:surface (pygame.Surface) – Surface to draw
Returns:None
draw_selection(surface)

Draw selection effect on widget.

Parameters:surface (pygame.Surface) – Surface to draw
Returns:None
get_alignment()

Returns widget alignment.

Returns:Widget align, see locals
Return type:str
get_attribute(key, default)

Get attribute value.

Parameters:
  • key (str) – Key of the attribute
  • default (Any) – Value if does not exists
Returns:

Attribute data

Return type:

Any

get_font_info()

Return a dict with the information of the widget font.

Returns:Dict, keys: size (int), name (str), color (tuple), selected_color (tuple), antialias (bool)
Return type:dict
get_id()

Returns the widget ID.

Returns:ID
Return type:str
get_margin()
Returns:Widget margin
Return type:tuple
get_menu()

Return menu reference (if exists).

Returns:Menu reference
Return type:pygame_menu.Menu
get_rect()

Return the Rect object, this forces the widget rendering

Returns:Widget rect
Return type:pygame.Rect
get_selected_time()

Return time the widget has been selected in miliseconds. If the widget is not currently selected, return 0.

Returns:Time in ms
Return type:float
get_selection_effect()
Returns:Selection effect
Return type:pygame_menu.widgets.core.Selection
get_title()

Return the widget title.

Returns:Widget title
Return type:str
get_value()

Return the value. If exception ValueError is raised, no value will be passed to the callbacks.

Returns:Value
Return type:Object
set_alignment(align)

Set the alignment of the widget.

Parameters:align (str) – Widget align, see locals
Returns:None
set_attribute(key, value)

Set widget attribute.

Parameters:
  • key (str) – Key of the attribute
  • value (Any) – Value of the attribute
Returns:

None

set_background_color(color, inflate=(0, 0))

Set widget background color.

Parameters:
Returns:

None

set_controls(joystick=True, mouse=True)

Enable interfaces to control the widget.

Parameters:
  • joystick (bool) – Use joystick
  • mouse (bool) – Use mouse
Returns:

None

set_font(font, font_size, color, selected_color, background_color, antialias=True)

Set the text font.

Parameters:
  • font (str, list) – Name or list of names for font (see pygame.font.match_font for precise format)
  • font_size (int) – Size of font in pixels
  • color (tuple) – Text color
  • selected_color (tuple) – Text color when widget is selected
  • background_color (tuple) – Font background color
  • antialias (bool) – Determines if antialias is applied to font (uses more processing power)
Returns:

None

set_margin(x, y)

Set Widget margin.

Parameters:
Returns:

None

set_max_width(width)

Set widget max width (column support) if force_fit_text is enabled.

Parameters:width (int, float, None) – Width in px, None if max width is disabled
Returns:None
set_menu(menu)

Set menu reference.

Parameters:menu (pygame_menu.Menu) – Menu object
Returns:None
set_position(posx, posy)

Set the position.

Parameters:
Returns:

None

set_selected(selected=True)

Mark the widget as selected.

Parameters:selected (bool) – Set item as selected
Returns:None
set_selection_effect(selection)

Set the selection effect handler.

Parameters:selection (pygame_menu.widgets.core.Selection) – Selection effect class
Returns:None
set_shadow(enabled=True, color=None, position=None, offset=None)

Show text shadow.

Parameters:
  • enabled (bool) – Shadow is enabled or not
  • color (list, None) – Shadow color
  • position (str, None) – Shadow position
  • offset (int, float, None) – Shadow offset
Returns:

None

set_sound(sound)

Set sound engine to the widget.

Parameters:sound (pygame_menu.sound.Sound) – Sound object
Returns:None
set_title(title)

Update the widget title.

Parameters:title (str) – New title
Returns:None
set_value(value)

Set the value.

Warning

This method does not fire the callbacks as it is called programmatically. This behavior is deliberately chosen to avoid infinite loops.

Parameters:value (Object) – Value to be set on the widget
Returns:None
surface_needs_update()

Checks if the widget width/height has changed because events. If so, return true and set the status of the widget (menu widget position needs update) as false. This method is used by .update() from Menu class.

Returns:True if the widget position has changed by events after the rendering.
Return type:bool
update(events)[source]

Update internal variable according to the given events list and fire the callbacks.

Parameters:events (list[pygame.event.Event]) – List of pygame events
Returns:True if updated
Return type:bool

Label

class pygame_menu.widgets.Label(title, label_id='')[source]

Bases: pygame_menu.widgets.core.widget.Widget

Label widget.

Parameters:
  • title (str) – Label title/text
  • label_id (str) – Label ID
apply(*args)

Run on_return callback when return event. A callback function receives the following arguments:

callback_func( value, *args, *widget._args, **widget._kwargs )
with:
  • value (if something is returned by get_value())
  • args given to this method
  • args of the widget
  • kwargs of the widget
Parameters:args – Extra arguments passed to the callback
Returns:None
change(*args)

Run on_change callback after change event is triggered. A callback function receives the following arguments:

callback_func( value, *args, *widget._args, **widget._kwargs )
with:
  • value (if something is returned by get_value())
  • args given to this method
  • args of the widget
  • kwargs of the widget
Parameters:args – Extra arguments passed to the callback
Returns:None
draw(surface)[source]

Draw the widget shape.

Parameters:surface (pygame.Surface) – Surface to draw
Returns:None
draw_selection(surface)

Draw selection effect on widget.

Parameters:surface (pygame.Surface) – Surface to draw
Returns:None
get_alignment()

Returns widget alignment.

Returns:Widget align, see locals
Return type:str
get_attribute(key, default)

Get attribute value.

Parameters:
  • key (str) – Key of the attribute
  • default (Any) – Value if does not exists
Returns:

Attribute data

Return type:

Any

get_font_info()

Return a dict with the information of the widget font.

Returns:Dict, keys: size (int), name (str), color (tuple), selected_color (tuple), antialias (bool)
Return type:dict
get_id()

Returns the widget ID.

Returns:ID
Return type:str
get_margin()
Returns:Widget margin
Return type:tuple
get_menu()

Return menu reference (if exists).

Returns:Menu reference
Return type:pygame_menu.Menu
get_rect()

Return the Rect object, this forces the widget rendering

Returns:Widget rect
Return type:pygame.Rect
get_selected_time()

Return time the widget has been selected in miliseconds. If the widget is not currently selected, return 0.

Returns:Time in ms
Return type:float
get_selection_effect()
Returns:Selection effect
Return type:pygame_menu.widgets.core.Selection
get_title()

Return the widget title.

Returns:Widget title
Return type:str
get_value()

Return the value. If exception ValueError is raised, no value will be passed to the callbacks.

Returns:Value
Return type:Object
set_alignment(align)

Set the alignment of the widget.

Parameters:align (str) – Widget align, see locals
Returns:None
set_attribute(key, value)

Set widget attribute.

Parameters:
  • key (str) – Key of the attribute
  • value (Any) – Value of the attribute
Returns:

None

set_background_color(color, inflate=(0, 0))

Set widget background color.

Parameters:
Returns:

None

set_controls(joystick=True, mouse=True)

Enable interfaces to control the widget.

Parameters:
  • joystick (bool) – Use joystick
  • mouse (bool) – Use mouse
Returns:

None

set_font(font, font_size, color, selected_color, background_color, antialias=True)

Set the text font.

Parameters:
  • font (str, list) – Name or list of names for font (see pygame.font.match_font for precise format)
  • font_size (int) – Size of font in pixels
  • color (tuple) – Text color
  • selected_color (tuple) – Text color when widget is selected
  • background_color (tuple) – Font background color
  • antialias (bool) – Determines if antialias is applied to font (uses more processing power)
Returns:

None

set_margin(x, y)

Set Widget margin.

Parameters:
Returns:

None

set_max_width(width)

Set widget max width (column support) if force_fit_text is enabled.

Parameters:width (int, float, None) – Width in px, None if max width is disabled
Returns:None
set_menu(menu)

Set menu reference.

Parameters:menu (pygame_menu.Menu) – Menu object
Returns:None
set_position(posx, posy)

Set the position.

Parameters:
Returns:

None

set_selected(selected=True)

Mark the widget as selected.

Parameters:selected (bool) – Set item as selected
Returns:None
set_selection_effect(selection)

Set the selection effect handler.

Parameters:selection (pygame_menu.widgets.core.Selection) – Selection effect class
Returns:None
set_shadow(enabled=True, color=None, position=None, offset=None)

Show text shadow.

Parameters:
  • enabled (bool) – Shadow is enabled or not
  • color (list, None) – Shadow color
  • position (str, None) – Shadow position
  • offset (int, float, None) – Shadow offset
Returns:

None

set_sound(sound)

Set sound engine to the widget.

Parameters:sound (pygame_menu.sound.Sound) – Sound object
Returns:None
set_title(title)

Update the widget title.

Parameters:title (str) – New title
Returns:None
set_value(value)

Set the value.

Warning

This method does not fire the callbacks as it is called programmatically. This behavior is deliberately chosen to avoid infinite loops.

Parameters:value (Object) – Value to be set on the widget
Returns:None
surface_needs_update()

Checks if the widget width/height has changed because events. If so, return true and set the status of the widget (menu widget position needs update) as false. This method is used by .update() from Menu class.

Returns:True if the widget position has changed by events after the rendering.
Return type:bool
update(events)[source]

Update internal variable according to the given events list and fire the callbacks.

Parameters:events (list[pygame.event.Event]) – List of pygame events
Returns:True if updated
Return type:bool

ScrollBar

class pygame_menu.widgets.ScrollBar(length, values_range, scrollbar_id='', orientation='__pygame_menu_orientation_horizontal__', slider_pad=0, slider_color=(200, 200, 200), page_ctrl_thick=20, page_ctrl_color=(235, 235, 235), onchange=None, onreturn=None, *args, **kwargs)[source]

Bases: pygame_menu.widgets.core.widget.Widget

A scroll bar include 3 separate controls: a slider, scroll arrows, and a page control:

  1. The slider provides a way to quickly go to any part of the document
  2. The scroll arrows are push buttons which can be used to accurately navigate to a particular place in a document.
  3. The page control is the area over which the slider is dragged (the scroll bar’s background). Clicking here moves the scroll bar towards the click by one “page”.

Warning

Arrows are not yet implemented

Parameters:
  • length (int) – Length of the page control
  • values_range (tuple, list) – Min and max values
  • scrollbar_id (str) – Bar identifier
  • orientation (str) – Bar orientation ORIENTATION_HORIZONTAL/ORIENTATION_VERTICAL
  • slider_pad (int, float) – Space between slider and page control
  • slider_color (tuple, list) – Color of the slider
  • page_ctrl_thick (int, float) – Page control thickness
  • page_ctrl_color (tuple, list) – Page control color
  • onchange (callable, None) – Callback when changing the selector
  • onreturn (callable, None) – Callback when pressing return button
apply(*args)

Run on_return callback when return event. A callback function receives the following arguments:

callback_func( value, *args, *widget._args, **widget._kwargs )
with:
  • value (if something is returned by get_value())
  • args given to this method
  • args of the widget
  • kwargs of the widget
Parameters:args – Extra arguments passed to the callback
Returns:None
change(*args)

Run on_change callback after change event is triggered. A callback function receives the following arguments:

callback_func( value, *args, *widget._args, **widget._kwargs )
with:
  • value (if something is returned by get_value())
  • args given to this method
  • args of the widget
  • kwargs of the widget
Parameters:args – Extra arguments passed to the callback
Returns:None
draw(surface)[source]

Draw the widget shape.

Parameters:surface (pygame.Surface) – Surface to draw
Returns:None
draw_selection(surface)

Draw selection effect on widget.

Parameters:surface (pygame.Surface) – Surface to draw
Returns:None
get_alignment()

Returns widget alignment.

Returns:Widget align, see locals
Return type:str
get_attribute(key, default)

Get attribute value.

Parameters:
  • key (str) – Key of the attribute
  • default (Any) – Value if does not exists
Returns:

Attribute data

Return type:

Any

get_font_info()

Return a dict with the information of the widget font.

Returns:Dict, keys: size (int), name (str), color (tuple), selected_color (tuple), antialias (bool)
Return type:dict
get_id()

Returns the widget ID.

Returns:ID
Return type:str
get_margin()
Returns:Widget margin
Return type:tuple
get_maximum()[source]
Returns:Return the greatest acceptable value
Return type:int
get_menu()

Return menu reference (if exists).

Returns:Menu reference
Return type:pygame_menu.Menu
get_minimum()[source]
Returns:Return the smallest acceptable value
Return type:int
get_orientation()[source]
Returns:Return the scroll bar orientation
Return type:str
get_page_step()[source]
Returns:Return amount that the value changes by when the user click on the page control surface
Return type:int
get_rect()

Return the Rect object, this forces the widget rendering

Returns:Widget rect
Return type:pygame.Rect
get_selected_time()

Return time the widget has been selected in miliseconds. If the widget is not currently selected, return 0.

Returns:Time in ms
Return type:float
get_selection_effect()
Returns:Selection effect
Return type:pygame_menu.widgets.core.Selection
get_title()

Return the widget title.

Returns:Widget title
Return type:str
get_value()[source]

Return the value according to the slider position.

Returns:Position in pixels
Return type:int
set_alignment(align)

Set the alignment of the widget.

Parameters:align (str) – Widget align, see locals
Returns:None
set_attribute(key, value)

Set widget attribute.

Parameters:
  • key (str) – Key of the attribute
  • value (Any) – Value of the attribute
Returns:

None

set_background_color(color, inflate=(0, 0))

Set widget background color.

Parameters:
Returns:

None

set_controls(joystick=True, mouse=True)

Enable interfaces to control the widget.

Parameters:
  • joystick (bool) – Use joystick
  • mouse (bool) – Use mouse
Returns:

None

set_font(font, font_size, color, selected_color, background_color, antialias=True)

Set the text font.

Parameters:
  • font (str, list) – Name or list of names for font (see pygame.font.match_font for precise format)
  • font_size (int) – Size of font in pixels
  • color (tuple) – Text color
  • selected_color (tuple) – Text color when widget is selected
  • background_color (tuple) – Font background color
  • antialias (bool) – Determines if antialias is applied to font (uses more processing power)
Returns:

None

set_length(value)[source]

Set the length of the page control area.

Parameters:value (int, float) – Length of the area
Returns:None
set_margin(x, y)

Set Widget margin.

Parameters:
Returns:

None

set_max_width(width)

Set widget max width (column support) if force_fit_text is enabled.

Parameters:width (int, float, None) – Width in px, None if max width is disabled
Returns:None
set_maximum(value)[source]

Set the greatest acceptable value.

Parameters:value (int, float) – Maximum value
Returns:None
set_menu(menu)

Set menu reference.

Parameters:menu (pygame_menu.Menu) – Menu object
Returns:None
set_minimum(value)[source]

Set the smallest acceptable value.

Parameters:value (int, float) – Minimum value
Returns:None
set_orientation(orientation)[source]

Set the scroll bar orientation to vertical or horizontal.

Parameters:orientation (str) – Widget orientation, could be ORIENTATION_HORIZONTAL / ORIENTATION_VERTICAL
Returns:None
set_page_step(value)[source]

Set the amount that the value changes by when the user click on the page control surface. The length of the slider is related to this value, and typically represents the proportion of the document area shown in a scrolling view.

Parameters:value (int, float) – Page step
Returns:None
set_position(posx, posy)

Set the position.

Parameters:
Returns:

None

set_selected(selected=True)

Mark the widget as selected.

Parameters:selected (bool) – Set item as selected
Returns:None
set_selection_effect(selection)

Set the selection effect handler.

Parameters:selection (pygame_menu.widgets.core.Selection) – Selection effect class
Returns:None
set_shadow(enabled=True, color=None, position=None, offset=None)

Show text shadow.

Parameters:
  • enabled (bool) – Shadow is enabled or not
  • color (list, None) – Shadow color
  • position (str, None) – Shadow position
  • offset (int, float, None) – Shadow offset
Returns:

None

set_sound(sound)

Set sound engine to the widget.

Parameters:sound (pygame_menu.sound.Sound) – Sound object
Returns:None
set_title(title)

Update the widget title.

Parameters:title (str) – New title
Returns:None
set_value(value)[source]

Set the position of the scrollbar.

Parameters:value (int, float) – Position
Returns:None
surface_needs_update()

Checks if the widget width/height has changed because events. If so, return true and set the status of the widget (menu widget position needs update) as false. This method is used by .update() from Menu class.

Returns:True if the widget position has changed by events after the rendering.
Return type:bool
update(events)[source]

Update internal variable according to the given events list and fire the callbacks.

Parameters:events (list[pygame.event.Event]) – List of pygame events
Returns:True if updated
Return type:bool

Selector

class pygame_menu.widgets.Selector(title, elements, selector_id='', default=0, onchange=None, onreturn=None, *args, **kwargs)[source]

Bases: pygame_menu.widgets.core.widget.Widget

Selector widget: several items with values and two functions that are executed when changing the selector (left/right) and pressing return button on the selected item.

The values of the selector are like:

values = [('Item1', a, b, c...), ('Item2', d, e, f..)]

The callbacks receive the current text, its index in the list, the associated arguments and all unknown keyword arguments:

onchange((current_text, index), a, b, c..., **kwargs)
onreturn((current_text, index), a, b, c..., **kwargs)
Parameters:
  • title (str) – Selector title
  • elements (list) – Elements of the selector
  • selector_id (str) – ID of the selector
  • default (int) – Index of default element to display
  • onchange (callable, None) – Callback when changing the selector
  • onreturn (callable, None) – Callback when pressing return button
  • kwargs (any) – Optional keyword-arguments for callbacks
apply(*args)

Run on_return callback when return event. A callback function receives the following arguments:

callback_func( value, *args, *widget._args, **widget._kwargs )
with:
  • value (if something is returned by get_value())
  • args given to this method
  • args of the widget
  • kwargs of the widget
Parameters:args – Extra arguments passed to the callback
Returns:None
change(*args)

Run on_change callback after change event is triggered. A callback function receives the following arguments:

callback_func( value, *args, *widget._args, **widget._kwargs )
with:
  • value (if something is returned by get_value())
  • args given to this method
  • args of the widget
  • kwargs of the widget
Parameters:args – Extra arguments passed to the callback
Returns:None
draw(surface)[source]

Draw the widget shape.

Parameters:surface (pygame.Surface) – Surface to draw
Returns:None
draw_selection(surface)

Draw selection effect on widget.

Parameters:surface (pygame.Surface) – Surface to draw
Returns:None
get_alignment()

Returns widget alignment.

Returns:Widget align, see locals
Return type:str
get_attribute(key, default)

Get attribute value.

Parameters:
  • key (str) – Key of the attribute
  • default (Any) – Value if does not exists
Returns:

Attribute data

Return type:

Any

get_font_info()

Return a dict with the information of the widget font.

Returns:Dict, keys: size (int), name (str), color (tuple), selected_color (tuple), antialias (bool)
Return type:dict
get_id()

Returns the widget ID.

Returns:ID
Return type:str
get_margin()
Returns:Widget margin
Return type:tuple
get_menu()

Return menu reference (if exists).

Returns:Menu reference
Return type:pygame_menu.Menu
get_rect()

Return the Rect object, this forces the widget rendering

Returns:Widget rect
Return type:pygame.Rect
get_selected_time()

Return time the widget has been selected in miliseconds. If the widget is not currently selected, return 0.

Returns:Time in ms
Return type:float
get_selection_effect()
Returns:Selection effect
Return type:pygame_menu.widgets.core.Selection
get_title()

Return the widget title.

Returns:Widget title
Return type:str
get_value()[source]

Return the current value of the selector at the selected index.

Returns:Value and index as a tuple, (value, index)
Return type:tuple
left()[source]

Move selector to left.

Returns:None
right()[source]

Move selector to right.

Returns:None
set_alignment(align)

Set the alignment of the widget.

Parameters:align (str) – Widget align, see locals
Returns:None
set_attribute(key, value)

Set widget attribute.

Parameters:
  • key (str) – Key of the attribute
  • value (Any) – Value of the attribute
Returns:

None

set_background_color(color, inflate=(0, 0))

Set widget background color.

Parameters:
Returns:

None

set_controls(joystick=True, mouse=True)

Enable interfaces to control the widget.

Parameters:
  • joystick (bool) – Use joystick
  • mouse (bool) – Use mouse
Returns:

None

set_font(font, font_size, color, selected_color, background_color, antialias=True)

Set the text font.

Parameters:
  • font (str, list) – Name or list of names for font (see pygame.font.match_font for precise format)
  • font_size (int) – Size of font in pixels
  • color (tuple) – Text color
  • selected_color (tuple) – Text color when widget is selected
  • background_color (tuple) – Font background color
  • antialias (bool) – Determines if antialias is applied to font (uses more processing power)
Returns:

None

set_margin(x, y)

Set Widget margin.

Parameters:
Returns:

None

set_max_width(width)

Set widget max width (column support) if force_fit_text is enabled.

Parameters:width (int, float, None) – Width in px, None if max width is disabled
Returns:None
set_menu(menu)

Set menu reference.

Parameters:menu (pygame_menu.Menu) – Menu object
Returns:None
set_position(posx, posy)

Set the position.

Parameters:
Returns:

None

set_selected(selected=True)

Mark the widget as selected.

Parameters:selected (bool) – Set item as selected
Returns:None
set_selection_effect(selection)

Set the selection effect handler.

Parameters:selection (pygame_menu.widgets.core.Selection) – Selection effect class
Returns:None
set_shadow(enabled=True, color=None, position=None, offset=None)

Show text shadow.

Parameters:
  • enabled (bool) – Shadow is enabled or not
  • color (list, None) – Shadow color
  • position (str, None) – Shadow position
  • offset (int, float, None) – Shadow offset
Returns:

None

set_sound(sound)

Set sound engine to the widget.

Parameters:sound (pygame_menu.sound.Sound) – Sound object
Returns:None
set_title(title)

Update the widget title.

Parameters:title (str) – New title
Returns:None
set_value(item)[source]

Set the current value of the widget, selecting the element that matches the text if item is a string, or the index of the position of item is an integer.

For example, if selector is [[‘a’,0],[‘b’,1],[‘a’,2]]:
  • widget.set_value(‘a’) -> Widget selects 0 (first match)
  • widget.set_value(2) -> Widget selects 2.
Parameters:item (str, int) – Item to select, can be a string or an integer.
Returns:None
surface_needs_update()

Checks if the widget width/height has changed because events. If so, return true and set the status of the widget (menu widget position needs update) as false. This method is used by .update() from Menu class.

Returns:True if the widget position has changed by events after the rendering.
Return type:bool
update(events)[source]

Update internal variable according to the given events list and fire the callbacks.

Parameters:events (list[pygame.event.Event]) – List of pygame events
Returns:True if updated
Return type:bool
update_elements(elements)[source]

Update selector elements.

Parameters:elements (Object) – Elements of the selector
Returns:None

TextInput

class pygame_menu.widgets.TextInput(title='', textinput_id='', input_type='__pygame_menu_input_text__', input_underline='', copy_paste_enable=True, cursor_color=(0, 0, 0), cursor_selection_color=(30, 30, 30, 100), cursor_selection_enable=True, history=50, maxchar=0, maxwidth=0, maxwidth_dynamically_update=True, onchange=None, onreturn=None, password=False, password_char='*', repeat_keys_initial_ms=450, repeat_keys_interval_ms=80, repeat_mouse_interval_ms=100, tab_size=4, text_ellipsis='...', valid_chars=None, *args, **kwargs)[source]

Bases: pygame_menu.widgets.core.widget.Widget

Text input widget.

Parameters:
  • title (str) – Text input title
  • textinput_id (str) – ID of the text input
  • input_type (str) – Type of data
  • input_underline (str) – Character drawn under the input
  • cursor_color (tuple) – Color of cursor
  • cursor_selection_color (tuple) – Selection box color
  • cursor_selection_enable (bool) – Enables selection of text
  • copy_paste_enable (bool) – Enables copy, paste and cut
  • history (int) – Maximum number of editions stored
  • maxchar (int) – Maximum length of input
  • maxwidth (int) – Maximum size of the text to be displayed (overflow), if 0 this feature is disabled
  • maxwidth_dynamically_update (bool) – Dynamically update maxwidth depending on char size
  • onchange (callable, None) – Callback when changing the selector
  • onreturn (callable, None) – Callback when pressing return button
  • password (bool) – Input string is displayed as a password
  • password_char (str) – Character used by password type
  • repeat_keys_initial_ms (int, float) – Time in ms before keys are repeated when held
  • repeat_keys_interval_ms (int, float) – Interval between key press repetition when held
  • repeat_mouse_interval_ms (int, float) – Interval between mouse events when held
  • tab_size (int) – Tab whitespace characters
  • text_ellipsis (str) – Ellipsis text when overflow occurs (input length exceeds maxwidth)
  • valid_chars (list) – List of chars that are valid, None if all chars are valid
  • kwargs (any) – Optional keyword-arguments for callbacks
apply(*args)

Run on_return callback when return event. A callback function receives the following arguments:

callback_func( value, *args, *widget._args, **widget._kwargs )
with:
  • value (if something is returned by get_value())
  • args given to this method
  • args of the widget
  • kwargs of the widget
Parameters:args – Extra arguments passed to the callback
Returns:None
change(*args)

Run on_change callback after change event is triggered. A callback function receives the following arguments:

callback_func( value, *args, *widget._args, **widget._kwargs )
with:
  • value (if something is returned by get_value())
  • args given to this method
  • args of the widget
  • kwargs of the widget
Parameters:args – Extra arguments passed to the callback
Returns:None
clear()[source]

Clear the current text.

Returns:None
draw(surface)[source]

Draw the widget shape.

Parameters:surface (pygame.Surface) – Surface to draw
Returns:None
draw_selection(surface)

Draw selection effect on widget.

Parameters:surface (pygame.Surface) – Surface to draw
Returns:None
get_alignment()

Returns widget alignment.

Returns:Widget align, see locals
Return type:str
get_attribute(key, default)

Get attribute value.

Parameters:
  • key (str) – Key of the attribute
  • default (Any) – Value if does not exists
Returns:

Attribute data

Return type:

Any

get_font_info()

Return a dict with the information of the widget font.

Returns:Dict, keys: size (int), name (str), color (tuple), selected_color (tuple), antialias (bool)
Return type:dict
get_id()

Returns the widget ID.

Returns:ID
Return type:str
get_margin()
Returns:Widget margin
Return type:tuple
get_menu()

Return menu reference (if exists).

Returns:Menu reference
Return type:pygame_menu.Menu
get_rect()

Return the Rect object, this forces the widget rendering

Returns:Widget rect
Return type:pygame.Rect
get_selected_time()

Return time the widget has been selected in miliseconds. If the widget is not currently selected, return 0.

Returns:Time in ms
Return type:float
get_selection_effect()
Returns:Selection effect
Return type:pygame_menu.widgets.core.Selection
get_title()

Return the widget title.

Returns:Widget title
Return type:str
get_value()[source]

Returns the value of the text.

Returns:Text inside the widget
Return type:str
set_alignment(align)

Set the alignment of the widget.

Parameters:align (str) – Widget align, see locals
Returns:None
set_attribute(key, value)

Set widget attribute.

Parameters:
  • key (str) – Key of the attribute
  • value (Any) – Value of the attribute
Returns:

None

set_background_color(color, inflate=(0, 0))

Set widget background color.

Parameters:
Returns:

None

set_controls(joystick=True, mouse=True)

Enable interfaces to control the widget.

Parameters:
  • joystick (bool) – Use joystick
  • mouse (bool) – Use mouse
Returns:

None

set_font(font, font_size, color, selected_color, background_color, antialias=True)

Set the text font.

Parameters:
  • font (str, list) – Name or list of names for font (see pygame.font.match_font for precise format)
  • font_size (int) – Size of font in pixels
  • color (tuple) – Text color
  • selected_color (tuple) – Text color when widget is selected
  • background_color (tuple) – Font background color
  • antialias (bool) – Determines if antialias is applied to font (uses more processing power)
Returns:

None

set_margin(x, y)

Set Widget margin.

Parameters:
Returns:

None

set_max_width(width)

Set widget max width (column support) if force_fit_text is enabled.

Parameters:width (int, float, None) – Width in px, None if max width is disabled
Returns:None
set_menu(menu)

Set menu reference.

Parameters:menu (pygame_menu.Menu) – Menu object
Returns:None
set_position(posx, posy)

Set the position.

Parameters:
Returns:

None

set_selected(selected=True)

Mark the widget as selected.

Parameters:selected (bool) – Set item as selected
Returns:None
set_selection_effect(selection)

Set the selection effect handler.

Parameters:selection (pygame_menu.widgets.core.Selection) – Selection effect class
Returns:None
set_shadow(enabled=True, color=None, position=None, offset=None)

Show text shadow.

Parameters:
  • enabled (bool) – Shadow is enabled or not
  • color (list, None) – Shadow color
  • position (str, None) – Shadow position
  • offset (int, float, None) – Shadow offset
Returns:

None

set_sound(sound)

Set sound engine to the widget.

Parameters:sound (pygame_menu.sound.Sound) – Sound object
Returns:None
set_title(title)

Update the widget title.

Parameters:title (str) – New title
Returns:None
set_value(text)[source]

Set the value of the text.

Parameters:text (str, int, float) – New text of the widget
Returns:None
surface_needs_update()

Checks if the widget width/height has changed because events. If so, return true and set the status of the widget (menu widget position needs update) as false. This method is used by .update() from Menu class.

Returns:True if the widget position has changed by events after the rendering.
Return type:bool
update(events)[source]

Update internal variable according to the given events list and fire the callbacks.

Parameters:events (list[pygame.event.Event]) – List of pygame events
Returns:True if updated
Return type:bool

VMargin

class pygame_menu.widgets.VMargin[source]

Bases: pygame_menu.widgets.core.widget.Widget

Vertical margin widget.

apply(*args)

Run on_return callback when return event. A callback function receives the following arguments:

callback_func( value, *args, *widget._args, **widget._kwargs )
with:
  • value (if something is returned by get_value())
  • args given to this method
  • args of the widget
  • kwargs of the widget
Parameters:args – Extra arguments passed to the callback
Returns:None
change(*args)

Run on_change callback after change event is triggered. A callback function receives the following arguments:

callback_func( value, *args, *widget._args, **widget._kwargs )
with:
  • value (if something is returned by get_value())
  • args given to this method
  • args of the widget
  • kwargs of the widget
Parameters:args – Extra arguments passed to the callback
Returns:None
draw(surface)[source]

Draw the widget shape.

Parameters:surface (pygame.Surface) – Surface to draw
Returns:None
draw_selection(surface)

Draw selection effect on widget.

Parameters:surface (pygame.Surface) – Surface to draw
Returns:None
get_alignment()

Returns widget alignment.

Returns:Widget align, see locals
Return type:str
get_attribute(key, default)

Get attribute value.

Parameters:
  • key (str) – Key of the attribute
  • default (Any) – Value if does not exists
Returns:

Attribute data

Return type:

Any

get_font_info()

Return a dict with the information of the widget font.

Returns:Dict, keys: size (int), name (str), color (tuple), selected_color (tuple), antialias (bool)
Return type:dict
get_id()

Returns the widget ID.

Returns:ID
Return type:str
get_margin()
Returns:Widget margin
Return type:tuple
get_menu()

Return menu reference (if exists).

Returns:Menu reference
Return type:pygame_menu.Menu
get_rect()

Return the Rect object, this forces the widget rendering

Returns:Widget rect
Return type:pygame.Rect
get_selected_time()

Return time the widget has been selected in miliseconds. If the widget is not currently selected, return 0.

Returns:Time in ms
Return type:float
get_selection_effect()
Returns:Selection effect
Return type:pygame_menu.widgets.core.Selection
get_title()

Return the widget title.

Returns:Widget title
Return type:str
get_value()

Return the value. If exception ValueError is raised, no value will be passed to the callbacks.

Returns:Value
Return type:Object
set_alignment(align)

Set the alignment of the widget.

Parameters:align (str) – Widget align, see locals
Returns:None
set_attribute(key, value)

Set widget attribute.

Parameters:
  • key (str) – Key of the attribute
  • value (Any) – Value of the attribute
Returns:

None

set_background_color(color, inflate=(0, 0))

Set widget background color.

Parameters:
Returns:

None

set_controls(joystick=True, mouse=True)

Enable interfaces to control the widget.

Parameters:
  • joystick (bool) – Use joystick
  • mouse (bool) – Use mouse
Returns:

None

set_font(font, font_size, color, selected_color, background_color, antialias=True)

Set the text font.

Parameters:
  • font (str, list) – Name or list of names for font (see pygame.font.match_font for precise format)
  • font_size (int) – Size of font in pixels
  • color (tuple) – Text color
  • selected_color (tuple) – Text color when widget is selected
  • background_color (tuple) – Font background color
  • antialias (bool) – Determines if antialias is applied to font (uses more processing power)
Returns:

None

set_margin(x, y)

Set Widget margin.

Parameters:
Returns:

None

set_max_width(width)

Set widget max width (column support) if force_fit_text is enabled.

Parameters:width (int, float, None) – Width in px, None if max width is disabled
Returns:None
set_menu(menu)

Set menu reference.

Parameters:menu (pygame_menu.Menu) – Menu object
Returns:None
set_position(posx, posy)

Set the position.

Parameters:
Returns:

None

set_selected(selected=True)

Mark the widget as selected.

Parameters:selected (bool) – Set item as selected
Returns:None
set_selection_effect(selection)

Set the selection effect handler.

Parameters:selection (pygame_menu.widgets.core.Selection) – Selection effect class
Returns:None
set_shadow(enabled=True, color=None, position=None, offset=None)

Show text shadow.

Parameters:
  • enabled (bool) – Shadow is enabled or not
  • color (list, None) – Shadow color
  • position (str, None) – Shadow position
  • offset (int, float, None) – Shadow offset
Returns:

None

set_sound(sound)

Set sound engine to the widget.

Parameters:sound (pygame_menu.sound.Sound) – Sound object
Returns:None
set_title(title)

Update the widget title.

Parameters:title (str) – New title
Returns:None
set_value(value)

Set the value.

Warning

This method does not fire the callbacks as it is called programmatically. This behavior is deliberately chosen to avoid infinite loops.

Parameters:value (Object) – Value to be set on the widget
Returns:None
surface_needs_update()

Checks if the widget width/height has changed because events. If so, return true and set the status of the widget (menu widget position needs update) as false. This method is used by .update() from Menu class.

Returns:True if the widget position has changed by events after the rendering.
Return type:bool
update(events)[source]

Update internal variable according to the given events list and fire the callbacks.

Parameters:events (list[pygame.event.Event]) – List of pygame events
Returns:True if updated
Return type:bool

About pygame-menu

This project does not have a mailing list and so the issues tab should be the first point of contact if wishing to discuss the project. If you have questions that you do not feel are relevant to the issues tab or just want to let me know what you think about the library, feel free to email me at pablo@ppizarror.com

License

The MIT License (MIT)

Copyright 2017-2020 Pablo Pizarro R. @ppizarror

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

The official license can be retrieved here

Contributors

Core developers:

Other contributors:

Ideas and contributions are always welcome. Any found bugs or enhancement suggestions should be posted on GitHub project page .

Indices and tables