
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):
- Import the required libraries
import pygame
import pygame_menu
- Initialize pygame
pygame.init()
surface = pygame.display.set_mode((600, 400))
- 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)
- Run your menu
menu.mainloop(surface)
Interested in going deeper into menu design ?
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:

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)
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 in px (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 (dict) – Optional keyword-arguments
Returns: Widget object or List of widgets if the text overflows
Return type:
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:

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)
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 in px (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 (dict) – Optional keyword-arguments
Returns: Widget object
Return type:
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:

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)
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 in px (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 (dict) – Additional keyword-arguments
Returns: Widget object
Return type:
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:

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)
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 in px (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 (dict) – Additional keyword-parameters
Returns: Widget object
Return type:
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:

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)
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 in px (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 (dict) – Additional keyword-parameters
Returns: Widget object
Return type:
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:

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)
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 in px (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 (dict) – Additional keyword-parameters
Returns: Widget object
Return type:
Add a vertical spacer¶
A vertical spacer can be added between two widgets to have a better visual rendering of the menu.
Example:

menu = pygame_menu.Menu(...)
menu.add_label('Text #1')
menu.add_vertical_margin(100)
menu.add_label('Text #2')
Adds a vertical margin to the current Menu.
Parameters: margin (int, float) – Vertical 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 |
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
Return the channel of the sound engine.
Returns: Channel Return type: pygame.mixer.Channel
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 the example sounds provided by the package.
Parameters: volume (float) – Volume of the sound, (0-1) Returns: None
Pause the current channel.
Returns: None
Play click mouse sound.
Returns: None
Play close menu sound.
Returns: None
Play error sound.
Returns: None
Play event sound.
Returns: None
Play event error sound.
Returns: None
Play key addition sound.
Returns: None
Play key deletion sound.
Returns: None
Play open menu sound.
Returns: None
Play widget selection sound.
Returns: None
Link a sound file to a sound type.
Parameters: Returns: The status of the sound load, True if the sound was loaded
Return type:
Stop the current the channel.
Returns: None
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 |
![]() |
pygame_menu.themes.THEME_BLUE |
![]() |
pygame_menu.themes.THEME_DARK |
![]() |
pygame_menu.themes.THEME_GREEN |
![]() |
pygame_menu.themes.THEME_ORANGE |
![]() |
pygame_menu.themes.THEME_SOLARIZED |
![]() |
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 |
![]() |
pygame_menu.font.FONT_BEBAS |
![]() |
pygame_menu.font.FONT_COMIC_NEUE |
![]() |
pygame_menu.font.FONT_FRANCHISE |
![]() |
pygame_menu.font.FONT_HELVETICA |
![]() |
pygame_menu.font.FONT_MUNRO |
![]() |
pygame_menu.font.FONT_NEVIS |
![]() |
pygame_menu.font.FONT_OPEN_SANS |
![]() |
pygame_menu.font.FONT_OPEN_SANS_BOLD |
![]() |
pygame_menu.font.FONT_OPEN_SANS_ITALIC |
![]() |
pygame_menu.font.FONT_OPEN_SANS_LIGHT |
![]() |
pygame_menu.font.FONT_PT_SERIF |
![]() |
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 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. Also 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
Creates a deep copy of the object.
Returns: Copied theme Return type: Theme
Modify menu background color with given opacity.
Parameters: opacity (int) – Opacity value, from 0 (transparent) to 1 (transparent) Returns: None
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
Gallery¶
Several examples are provided with the pygame_menu
library.
To run the examples, simply execute these commands in a terminal:
$> python -m pygame_menu.examples.simple
$> python -m pygame_menu.examples.game_selector
$> python -m pygame_menu.examples.multi_input
$> python -m pygame_menu.examples.scroll_menu
$> python -m pygame_menu.examples.timer_clock
Them can also be imported as follows:
from pygame_menu.examples.example import main
main()
Examples can also be found in the Github repo.
Simple example¶

Multiple input example¶

Columns example¶

Game selector example¶

Timer clock example¶

Migration Guide - v2 to v3¶
- Removed from library
- Renamed library
pygameMenu
topygame_menu
- Removed all configuration variables from
pygameMenu.config
. - Removed
TextMenu
, useMenu
andadd_label()
method instead
- Renamed library
- 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)
- Menu manage the event loop and drawing using
- Removed from Menu class
add_option()
, useadd_button()
insteadset_fps()
, usefps_limit
frommainloop()
instead- Constructor parameters:
bgfun
, now this function is required byMenu.mainloop()
color_selected
, moved toselection_color
ofpygame_menu.themes.Theme
dopause
, now user can control this behaviour usingupdate()
ormainloop()
draw_region_x
, moved towidget_offset
ofpygame_menu.themes.Theme
draw_region_y
, moved towidget_offset
ofpygame_menu.themes.Theme
draw_select
, moved towidget_selection_effect
ofpygame_menu.themes.Theme
font_color
, moved towidget_font_color
ofpygame_menu.themes.Theme
font_size_title
, moved totitle_font_size
ofpygame_menu.themes.Theme
font_size
, moved towidget_font_size
ofpygame_menu.themes.Theme
font_title
, moved totitle_font
ofpygame_menu.themes.Theme
font
, moved towidget_font
ofpygame_menu.themes.Theme
fps
, usefps_limit
frommainloop()
insteadmenu_alpha
, now each color ofpygame_menu.themes.Theme
can be defined with opacitymenu_color_title
, moved totitle_background_color
ofpygame_menu.themes.Theme
menu_color
, moved tobackground_color
ofpygame_menu.themes.Theme
menu_height
, useheight
menu_width
, useheight
option_margin
, moved towidget_margin
ofpygame_menu.themes.Theme
option_shadow_offset
, moved towidget_shadow_offset
ofpygame_menu.themes.Theme
option_shadow_position
, moved towidget_shadow_position
ofpygame_menu.themes.Theme
option_shadow
, moved towidget_shadow
ofpygame_menu.themes.Theme
rect_width
, now change selection effect frompygame_menu.themes.Theme
surface
, now pygame surface is only required bymainloop()
andupdate()
title_offsetx
, moved totitle_offset
ofpygame_menu.themes.Theme
title_offsety
, moved totitle_offset
ofpygame_menu.themes.Theme
window_width
andwindow_height
parameters
- Renamed Menu method parameters
element_name
andelement
fromadd_button()
totitle
andaction
values
fromadd_selector()
toitems
widget_id
fromadd_button()
tobutton_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:
- Each time a new Widget is added, regenerate their position.
- Widgets can either be active or inactive. The active widget will catch user events as keyboard or mouse.
- Active widgets have a decoration, named Selection
- The drawing process is:
- Draw Menu background color/image
- Draw all widgets
- Draw Selection decoration on selected widget surface area
- Draw menubar
- 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:
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(...))
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¶
Bases:
pygame_menu.widgets.core.widget.Widget
Button widget.
Parameters: 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 byget_value()
)args
given to this methodargs
of the widgetkwargs
of the widget
Parameters: - args – Extra arguments passed to the callback
- args – any
Returns: None
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 byget_value()
)args
given to this methodargs
of the widgetkwargs
of the widget
Parameters: - args – Extra arguments passed to the callback
- args – any
Returns: None
Draw the widget shape.
Parameters: surface ( pygame.Surface
) – Surface to drawReturns: None
Draw selection effect on widget.
Parameters: surface ( pygame.Surface
) – Surface to drawReturns: None
Return the widget alignment.
Returns: Widget align, see locals Return type: str
Get attribute value.
Parameters: - key (str) – Key of the attribute
- default (any) – Value if does not exists
Returns: Attribute data
Return type: any
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
Return the widget ID.
Returns: Widget ID Return type: str
Return the widget margin.
Returns: Widget margin Return type: tuple
Return the menu reference (if exists).
Returns: Menu reference Return type: pygame_menu.Menu
Return the Rect object, this forces the widget rendering.
Returns: Widget rect Return type: pygame.Rect
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
Return the selection effect.
Returns: Selection effect Return type: pygame_menu.widgets.core.Selection
Return the widget title.
Returns: Widget title Return type: str
Return the value. If exception
ValueError
is raised, no value will be passed to the callbacks.Returns: Widget data value Return type: Object
Set the alignment of the widget.
Parameters: align (str) – Widget align, see locals Returns: None
Set widget attribute.
Parameters: - key (str) – Key of the attribute
- value (any) – Value of the attribute
Returns: None
Set widget background color.
Parameters: - color (tuple, list,
pygame_menu.baseimage.BaseImage
, None) – Widget background color - inflate (tuple, list) – Inflate background in x,y
Returns: None
- color (tuple, list,
Enable interfaces to control the widget.
Parameters: Returns: None
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 Widget margin.
Parameters: Returns: None
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 the menu reference.
Parameters: menu ( pygame_menu.Menu
) – Menu objectReturns: None
Set the position.
Parameters: Returns: None
Mark the widget as selected.
Parameters: selected (bool) – Set item as selected Returns: None
Set the selection effect handler.
Parameters: selection ( pygame_menu.widgets.core.Selection
) – Selection effect classReturns: None
Show text shadow.
Parameters: Returns: None
Set sound engine to the widget.
Parameters: sound ( pygame_menu.sound.Sound
) – Sound objectReturns: None
Update the widget title.
Parameters: title (str) – New title Returns: None
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
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 internal variable according to the given events list and fire the callbacks.
Parameters: events (list[ pygame.event.Event
]) – List of pygame eventsReturns: True if updated Return type: bool
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 (any) – Arguments used by the function once triggered
Returns: None
ColorInput¶
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 (dict) – Optional keyword-arguments for callbacks
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 byget_value()
)args
given to this methodargs
of the widgetkwargs
of the widget
Parameters: - args – Extra arguments passed to the callback
- args – any
Returns: None
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 byget_value()
)args
given to this methodargs
of the widgetkwargs
of the widget
Parameters: - args – Extra arguments passed to the callback
- args – any
Returns: None
Clear the current text.
Returns: None
Draw the widget shape.
Parameters: surface ( pygame.Surface
) – Surface to drawReturns: None
Draw selection effect on widget.
Parameters: surface ( pygame.Surface
) – Surface to drawReturns: None
Return the widget alignment.
Returns: Widget align, see locals Return type: str
Get attribute value.
Parameters: - key (str) – Key of the attribute
- default (any) – Value if does not exists
Returns: Attribute data
Return type: any
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
Return the widget ID.
Returns: Widget ID Return type: str
Return the widget margin.
Returns: Widget margin Return type: tuple
Return the menu reference (if exists).
Returns: Menu reference Return type: pygame_menu.Menu
Return the Rect object, this forces the widget rendering.
Returns: Widget rect Return type: pygame.Rect
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
Return the selection effect.
Returns: Selection effect Return type: pygame_menu.widgets.core.Selection
Return the widget title.
Returns: Widget title Return type: str
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
Return true if the current value of the input is a valid color or not.
Returns: True if valid Return type: bool
Set the alignment of the widget.
Parameters: align (str) – Widget align, see locals Returns: None
Set widget attribute.
Parameters: - key (str) – Key of the attribute
- value (any) – Value of the attribute
Returns: None
Set widget background color.
Parameters: - color (tuple, list,
pygame_menu.baseimage.BaseImage
, None) – Widget background color - inflate (tuple, list) – Inflate background in x,y
Returns: None
- color (tuple, list,
Enable interfaces to control the widget.
Parameters: Returns: None
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 Widget margin.
Parameters: Returns: None
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 the menu reference.
Parameters: menu ( pygame_menu.Menu
) – Menu objectReturns: None
Set the position.
Parameters: Returns: None
Mark the widget as selected.
Parameters: selected (bool) – Set item as selected Returns: None
Set the selection effect handler.
Parameters: selection ( pygame_menu.widgets.core.Selection
) – Selection effect classReturns: None
Show text shadow.
Parameters: Returns: None
Set sound engine to the widget.
Parameters: sound ( pygame_menu.sound.Sound
) – Sound objectReturns: None
Update the widget title.
Parameters: title (str) – New title Returns: None
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 internal variable according to the given events list and fire the callbacks.
Parameters: events (list[ pygame.event.Event
]) – List of pygame eventsReturns: True if updated Return type: bool
Image¶
Bases:
pygame_menu.widgets.core.widget.Widget
Image widget.
Parameters: 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 byget_value()
)args
given to this methodargs
of the widgetkwargs
of the widget
Parameters: - args – Extra arguments passed to the callback
- args – any
Returns: None
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 byget_value()
)args
given to this methodargs
of the widgetkwargs
of the widget
Parameters: - args – Extra arguments passed to the callback
- args – any
Returns: None
Draw the widget shape.
Parameters: surface ( pygame.Surface
) – Surface to drawReturns: None
Draw selection effect on widget.
Parameters: surface ( pygame.Surface
) – Surface to drawReturns: None
Return the widget alignment.
Returns: Widget align, see locals Return type: str
Get attribute value.
Parameters: - key (str) – Key of the attribute
- default (any) – Value if does not exists
Returns: Attribute data
Return type: any
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
Return the widget ID.
Returns: Widget ID Return type: str
Return the widget margin.
Returns: Widget margin Return type: tuple
Return the menu reference (if exists).
Returns: Menu reference Return type: pygame_menu.Menu
Return the Rect object, this forces the widget rendering.
Returns: Widget rect Return type: pygame.Rect
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
Return the selection effect.
Returns: Selection effect Return type: pygame_menu.widgets.core.Selection
Return the widget title.
Returns: Widget title Return type: str
Return the value. If exception
ValueError
is raised, no value will be passed to the callbacks.Returns: Widget data value Return type: Object
Set the alignment of the widget.
Parameters: align (str) – Widget align, see locals Returns: None
Set widget attribute.
Parameters: - key (str) – Key of the attribute
- value (any) – Value of the attribute
Returns: None
Set widget background color.
Parameters: - color (tuple, list,
pygame_menu.baseimage.BaseImage
, None) – Widget background color - inflate (tuple, list) – Inflate background in x,y
Returns: None
- color (tuple, list,
Enable interfaces to control the widget.
Parameters: Returns: None
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 Widget margin.
Parameters: Returns: None
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 the menu reference.
Parameters: menu ( pygame_menu.Menu
) – Menu objectReturns: None
Set the position.
Parameters: Returns: None
Mark the widget as selected.
Parameters: selected (bool) – Set item as selected Returns: None
Set the selection effect handler.
Parameters: selection ( pygame_menu.widgets.core.Selection
) – Selection effect classReturns: None
Show text shadow.
Parameters: Returns: None
Set sound engine to the widget.
Parameters: sound ( pygame_menu.sound.Sound
) – Sound objectReturns: None
Update the widget title.
Parameters: title (str) – New title Returns: None
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
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 internal variable according to the given events list and fire the callbacks.
Parameters: events (list[ pygame.event.Event
]) – List of pygame eventsReturns: True if updated Return type: bool
Label¶
Bases:
pygame_menu.widgets.core.widget.Widget
Label widget.
Parameters: 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 byget_value()
)args
given to this methodargs
of the widgetkwargs
of the widget
Parameters: - args – Extra arguments passed to the callback
- args – any
Returns: None
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 byget_value()
)args
given to this methodargs
of the widgetkwargs
of the widget
Parameters: - args – Extra arguments passed to the callback
- args – any
Returns: None
Draw the widget shape.
Parameters: surface ( pygame.Surface
) – Surface to drawReturns: None
Draw selection effect on widget.
Parameters: surface ( pygame.Surface
) – Surface to drawReturns: None
Return the widget alignment.
Returns: Widget align, see locals Return type: str
Get attribute value.
Parameters: - key (str) – Key of the attribute
- default (any) – Value if does not exists
Returns: Attribute data
Return type: any
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
Return the widget ID.
Returns: Widget ID Return type: str
Return the widget margin.
Returns: Widget margin Return type: tuple
Return the menu reference (if exists).
Returns: Menu reference Return type: pygame_menu.Menu
Return the Rect object, this forces the widget rendering.
Returns: Widget rect Return type: pygame.Rect
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
Return the selection effect.
Returns: Selection effect Return type: pygame_menu.widgets.core.Selection
Return the widget title.
Returns: Widget title Return type: str
Return the value. If exception
ValueError
is raised, no value will be passed to the callbacks.Returns: Widget data value Return type: Object
Set the alignment of the widget.
Parameters: align (str) – Widget align, see locals Returns: None
Set widget attribute.
Parameters: - key (str) – Key of the attribute
- value (any) – Value of the attribute
Returns: None
Set widget background color.
Parameters: - color (tuple, list,
pygame_menu.baseimage.BaseImage
, None) – Widget background color - inflate (tuple, list) – Inflate background in x,y
Returns: None
- color (tuple, list,
Enable interfaces to control the widget.
Parameters: Returns: None
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 Widget margin.
Parameters: Returns: None
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 the menu reference.
Parameters: menu ( pygame_menu.Menu
) – Menu objectReturns: None
Set the position.
Parameters: Returns: None
Mark the widget as selected.
Parameters: selected (bool) – Set item as selected Returns: None
Set the selection effect handler.
Parameters: selection ( pygame_menu.widgets.core.Selection
) – Selection effect classReturns: None
Show text shadow.
Parameters: Returns: None
Set sound engine to the widget.
Parameters: sound ( pygame_menu.sound.Sound
) – Sound objectReturns: None
Update the widget title.
Parameters: title (str) – New title Returns: None
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
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 internal variable according to the given events list and fire the callbacks.
Parameters: events (list[ pygame.event.Event
]) – List of pygame eventsReturns: True if updated Return type: bool
ScrollBar¶
Bases:
pygame_menu.widgets.core.widget.Widget
A scroll bar include 3 separate controls: a slider, scroll arrows, and a page control:
- The slider provides a way to quickly go to any part of the document
- The scroll arrows are push buttons which can be used to accurately navigate to a particular place in a document.
- 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
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 byget_value()
)args
given to this methodargs
of the widgetkwargs
of the widget
Parameters: - args – Extra arguments passed to the callback
- args – any
Returns: None
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 byget_value()
)args
given to this methodargs
of the widgetkwargs
of the widget
Parameters: - args – Extra arguments passed to the callback
- args – any
Returns: None
Draw the widget shape.
Parameters: surface ( pygame.Surface
) – Surface to drawReturns: None
Draw selection effect on widget.
Parameters: surface ( pygame.Surface
) – Surface to drawReturns: None
Return the widget alignment.
Returns: Widget align, see locals Return type: str
Get attribute value.
Parameters: - key (str) – Key of the attribute
- default (any) – Value if does not exists
Returns: Attribute data
Return type: any
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
Return the widget ID.
Returns: Widget ID Return type: str
Return the widget margin.
Returns: Widget margin Return type: tuple
Return the greatest acceptable value.
Returns: Greatest acceptable value Return type: int
Return the menu reference (if exists).
Returns: Menu reference Return type: pygame_menu.Menu
Return the smallest acceptable value.
Returns: Smallest acceptable value Return type: int
Return the scrollbar orientation (pygame-menu locals).
Returns: Scrollbar orientation Return type: str
Return amount that the value changes by when the user click on the page control surface.
Returns: Page step Return type: int
Return the Rect object, this forces the widget rendering.
Returns: Widget rect Return type: pygame.Rect
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
Return the selection effect.
Returns: Selection effect Return type: pygame_menu.widgets.core.Selection
Return the widget title.
Returns: Widget title Return type: str
Return the value according to the slider position.
Returns: Position in pixels Return type: int
Set the alignment of the widget.
Parameters: align (str) – Widget align, see locals Returns: None
Set widget attribute.
Parameters: - key (str) – Key of the attribute
- value (any) – Value of the attribute
Returns: None
Set widget background color.
Parameters: - color (tuple, list,
pygame_menu.baseimage.BaseImage
, None) – Widget background color - inflate (tuple, list) – Inflate background in x,y
Returns: None
- color (tuple, list,
Enable interfaces to control the widget.
Parameters: Returns: None
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 the length of the page control area.
Parameters: value (int, float) – Length of the area Returns: None
Set Widget margin.
Parameters: Returns: None
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 the menu reference.
Parameters: menu ( pygame_menu.Menu
) – Menu objectReturns: None
Set the scroll bar orientation to vertical or horizontal.
Parameters: orientation (str) – Widget orientation, could be ORIENTATION_HORIZONTAL / ORIENTATION_VERTICAL Returns: None
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 the position.
Parameters: Returns: None
Mark the widget as selected.
Parameters: selected (bool) – Set item as selected Returns: None
Set the selection effect handler.
Parameters: selection ( pygame_menu.widgets.core.Selection
) – Selection effect classReturns: None
Show text shadow.
Parameters: Returns: None
Set sound engine to the widget.
Parameters: sound ( pygame_menu.sound.Sound
) – Sound objectReturns: None
Update the widget title.
Parameters: title (str) – New title Returns: None
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 internal variable according to the given events list and fire the callbacks.
Parameters: events (list[ pygame.event.Event
]) – List of pygame eventsReturns: True if updated Return type: bool
Selector¶
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 (dict) – Optional keyword-arguments for callbacks
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 byget_value()
)args
given to this methodargs
of the widgetkwargs
of the widget
Parameters: - args – Extra arguments passed to the callback
- args – any
Returns: None
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 byget_value()
)args
given to this methodargs
of the widgetkwargs
of the widget
Parameters: - args – Extra arguments passed to the callback
- args – any
Returns: None
Draw the widget shape.
Parameters: surface ( pygame.Surface
) – Surface to drawReturns: None
Draw selection effect on widget.
Parameters: surface ( pygame.Surface
) – Surface to drawReturns: None
Return the widget alignment.
Returns: Widget align, see locals Return type: str
Get attribute value.
Parameters: - key (str) – Key of the attribute
- default (any) – Value if does not exists
Returns: Attribute data
Return type: any
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
Return the widget ID.
Returns: Widget ID Return type: str
Return the widget margin.
Returns: Widget margin Return type: tuple
Return the menu reference (if exists).
Returns: Menu reference Return type: pygame_menu.Menu
Return the Rect object, this forces the widget rendering.
Returns: Widget rect Return type: pygame.Rect
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
Return the selection effect.
Returns: Selection effect Return type: pygame_menu.widgets.core.Selection
Return the widget title.
Returns: Widget title Return type: str
Return the current value of the selector at the selected index.
Returns: Value and index as a tuple, (value, index) Return type: tuple
Move selector to left.
Returns: None
Move selector to right.
Returns: None
Set the alignment of the widget.
Parameters: align (str) – Widget align, see locals Returns: None
Set widget attribute.
Parameters: - key (str) – Key of the attribute
- value (any) – Value of the attribute
Returns: None
Set widget background color.
Parameters: - color (tuple, list,
pygame_menu.baseimage.BaseImage
, None) – Widget background color - inflate (tuple, list) – Inflate background in x,y
Returns: None
- color (tuple, list,
Enable interfaces to control the widget.
Parameters: Returns: None
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 Widget margin.
Parameters: Returns: None
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 the menu reference.
Parameters: menu ( pygame_menu.Menu
) – Menu objectReturns: None
Set the position.
Parameters: Returns: None
Mark the widget as selected.
Parameters: selected (bool) – Set item as selected Returns: None
Set the selection effect handler.
Parameters: selection ( pygame_menu.widgets.core.Selection
) – Selection effect classReturns: None
Show text shadow.
Parameters: Returns: None
Set sound engine to the widget.
Parameters: sound ( pygame_menu.sound.Sound
) – Sound objectReturns: None
Update the widget title.
Parameters: title (str) – New title Returns: None
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
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 internal variable according to the given events list and fire the callbacks.
Parameters: events (list[ pygame.event.Event
]) – List of pygame eventsReturns: True if updated Return type: bool
Update selector elements.
Parameters: elements (Object) – Elements of the selector Returns: None
TextInput¶
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 (dict) – Optional keyword-arguments for callbacks
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 byget_value()
)args
given to this methodargs
of the widgetkwargs
of the widget
Parameters: - args – Extra arguments passed to the callback
- args – any
Returns: None
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 byget_value()
)args
given to this methodargs
of the widgetkwargs
of the widget
Parameters: - args – Extra arguments passed to the callback
- args – any
Returns: None
Clear the current text.
Returns: None
Draw the widget shape.
Parameters: surface ( pygame.Surface
) – Surface to drawReturns: None
Draw selection effect on widget.
Parameters: surface ( pygame.Surface
) – Surface to drawReturns: None
Return the widget alignment.
Returns: Widget align, see locals Return type: str
Get attribute value.
Parameters: - key (str) – Key of the attribute
- default (any) – Value if does not exists
Returns: Attribute data
Return type: any
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
Return the widget ID.
Returns: Widget ID Return type: str
Return the widget margin.
Returns: Widget margin Return type: tuple
Return the menu reference (if exists).
Returns: Menu reference Return type: pygame_menu.Menu
Return the Rect object, this forces the widget rendering.
Returns: Widget rect Return type: pygame.Rect
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
Return the selection effect.
Returns: Selection effect Return type: pygame_menu.widgets.core.Selection
Return the widget title.
Returns: Widget title Return type: str
Return the value of the text.
Returns: Text inside the widget Return type: str
Set the alignment of the widget.
Parameters: align (str) – Widget align, see locals Returns: None
Set widget attribute.
Parameters: - key (str) – Key of the attribute
- value (any) – Value of the attribute
Returns: None
Set widget background color.
Parameters: - color (tuple, list,
pygame_menu.baseimage.BaseImage
, None) – Widget background color - inflate (tuple, list) – Inflate background in x,y
Returns: None
- color (tuple, list,
Enable interfaces to control the widget.
Parameters: Returns: None
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 Widget margin.
Parameters: Returns: None
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 the menu reference.
Parameters: menu ( pygame_menu.Menu
) – Menu objectReturns: None
Set the position.
Parameters: Returns: None
Mark the widget as selected.
Parameters: selected (bool) – Set item as selected Returns: None
Set the selection effect handler.
Parameters: selection ( pygame_menu.widgets.core.Selection
) – Selection effect classReturns: None
Show text shadow.
Parameters: Returns: None
Set sound engine to the widget.
Parameters: sound ( pygame_menu.sound.Sound
) – Sound objectReturns: None
Update the widget title.
Parameters: title (str) – New title Returns: None
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 internal variable according to the given events list and fire the callbacks.
Parameters: events (list[ pygame.event.Event
]) – List of pygame eventsReturns: True if updated Return type: bool
VMargin¶
Bases:
pygame_menu.widgets.core.widget.Widget
Vertical margin widget.
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 byget_value()
)args
given to this methodargs
of the widgetkwargs
of the widget
Parameters: - args – Extra arguments passed to the callback
- args – any
Returns: None
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 byget_value()
)args
given to this methodargs
of the widgetkwargs
of the widget
Parameters: - args – Extra arguments passed to the callback
- args – any
Returns: None
Draw the widget shape.
Parameters: surface ( pygame.Surface
) – Surface to drawReturns: None
Draw selection effect on widget.
Parameters: surface ( pygame.Surface
) – Surface to drawReturns: None
Return the widget alignment.
Returns: Widget align, see locals Return type: str
Get attribute value.
Parameters: - key (str) – Key of the attribute
- default (any) – Value if does not exists
Returns: Attribute data
Return type: any
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
Return the widget ID.
Returns: Widget ID Return type: str
Return the widget margin.
Returns: Widget margin Return type: tuple
Return the menu reference (if exists).
Returns: Menu reference Return type: pygame_menu.Menu
Return the Rect object, this forces the widget rendering.
Returns: Widget rect Return type: pygame.Rect
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
Return the selection effect.
Returns: Selection effect Return type: pygame_menu.widgets.core.Selection
Return the widget title.
Returns: Widget title Return type: str
Return the value. If exception
ValueError
is raised, no value will be passed to the callbacks.Returns: Widget data value Return type: Object
Set the alignment of the widget.
Parameters: align (str) – Widget align, see locals Returns: None
Set widget attribute.
Parameters: - key (str) – Key of the attribute
- value (any) – Value of the attribute
Returns: None
Set widget background color.
Parameters: - color (tuple, list,
pygame_menu.baseimage.BaseImage
, None) – Widget background color - inflate (tuple, list) – Inflate background in x,y
Returns: None
- color (tuple, list,
Enable interfaces to control the widget.
Parameters: Returns: None
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 Widget margin.
Parameters: Returns: None
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 the menu reference.
Parameters: menu ( pygame_menu.Menu
) – Menu objectReturns: None
Set the position.
Parameters: Returns: None
Mark the widget as selected.
Parameters: selected (bool) – Set item as selected Returns: None
Set the selection effect handler.
Parameters: selection ( pygame_menu.widgets.core.Selection
) – Selection effect classReturns: None
Show text shadow.
Parameters: Returns: None
Set sound engine to the widget.
Parameters: sound ( pygame_menu.sound.Sound
) – Sound objectReturns: None
Update the widget title.
Parameters: title (str) – New title Returns: None
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
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 internal variable according to the given events list and fire the callbacks.
Parameters: events (list[ pygame.event.Event
]) – List of pygame eventsReturns: True if updated Return type: bool