
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 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)back_count
Number of menus to go back if action is :py:class:`pygame_menu.events.BACK event, default is 1 (int)background_color
Color of the background (tuple, list,pygame_menu.baseimage.BaseImage
)background_inflate
Inflate background in (x,y) in px (tuple, list)button_id
Widget ID (str)font_background_color
Widget font background color (tuple, list, None)font_color
Widget font color (tuple, list)font_name
Widget font (str)font_size
Font size of the widget (int)margin
Widget (left,bottom) margin in px (tuple, list)padding
Widget padding according to CSS rules (int, float, list, tuple). General shape: (top,right,bottom,left)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)
Parameters: - title (str, any) – 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, any) – Optional 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 in (x,y) in px (tuple, list)font_background_color
Widget font background color (tuple, list, None)font_color
Widget font color (tuple, list)font_name
Widget font (str)font_size
Font size of the widget (int)margin
Widget (left,bottom) margin in px (tuple, list)padding
Widget padding according to CSS rules (int, float, list, tuple). General shape: (top, right, bottom, left)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)
Parameters: - title (str, any) – 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, any) – Optional keyword arguments
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 in (x,y) in px (tuple, list)font_background_color
Widget font background color (tuple, list, None)font_color
Widget font color (tuple, list)font_name
Widget font (str)font_size
Font size of the widget (int)margin
Widget (left,bottom) margin in px (tuple, list)padding
Widget padding according to CSS rules (int, float, list, tuple). General shape: (top,right,bottom,left)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)
Parameters: - title (str, any) – 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 values of the color text
- onreturn (callable, None) – Function when pressing return on the color text input
- previsualization_width (int, float) – Previsualization width as a factor of the height
- kwargs (dict, any) – Optional keyword arguments
Returns: Widget object
Return type:
Add a generic widget¶
A user-created widget can also be added to the menu. The widget must be fully configured before the addition.
Example:
def check_color(value):
print('New color:', value)
widget_label = pygame_menu.widgets.Label(...)
widget_image = pygame_menu.widgets.Image(...)
# This applies menu default widget configuration
menu.add_generic_widget(widget_label, configure_defaults=True)
# Adds menu without default configuration
menu.add_generic_widget(widget_image)
Add generic widget to current Menu.
Note
The widget should be fully configured by the user: font, padding, etc.
Warning
Unintended behaviours may happen while using this method, use only with caution. Specially while creating nested submenus with buttons.
Parameters: - widget (
pygame_menu.widgets.core.widget.Widget
) – Widget to be added - configure_defaults (bool) – Apply defaults widget configuration
Returns: None
- widget (
Add a label¶
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 in (x,y) in px (tuple, list)font_background_color
Widget font background color (tuple, list, None)font_color
Widget font color (tuple, list)font_name
Widget font (str)font_size
Font size of the widget (int)margin
Widget (left,bottom) margin in px (tuple, list)padding
Widget padding according to CSS rules (int, float, list, tuple). General shape: (top,right,bottom,left)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)
Parameters: - title (str, any) – Text to be displayed
- label_id (str) – ID of the label
- max_char (int) – Split the title in several labels if the string length exceeds
max_char
; (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, any) – Optional keyword arguments
Returns: Widget object, or List of widgets if the text overflows
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 in (x,y) in px (tuple, list)font_background_color
Widget font background color (tuple, list, None)font_color
Widget font color (tuple, list)font_name
Widget font (str)font_size
Font size of the widget (int)margin
Widget (left,bottom) margin in px (tuple, list)padding
Widget padding according to CSS rules (int, float, list, tuple). General shape: (top,right,bottom,left)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)
Parameters: - title (str, any) – 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
- input_underline_len (int) – Total of characters to be drawn under the input. If 0 this number is computed automatically to fit the font
- maxchar (int) – Maximum length of string, if 0 there’s no limit
- maxwidth (int) – Maximum size of the text widget (in number of chars), if 0 there’s no limit
- onchange (callable, None) – Callback when changing the text input
- onreturn (callable, None) – Callback when pressing return on the text input
- 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, None) – List of authorized chars.
None
if all chars are valid - kwargs (dict, any) – Optional keyword arguments
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: Returns: Widget object
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 in (x,y) in px (tuple, list)margin
Widget (left,bottom) margin in px (tuple, list)padding
Widget padding according to CSS rules (int, float, list, tuple). General shape: (top, right, bottom, left)selection_color
Widget selection color (tuple, list)selection_effect
Widget selection effect (pygame_menu.widgets.core.Selection
)
Parameters: - image_path (str,
pathlib.Path
,pygame_menu.baseimage.BaseImage
) – Path of the image (file) or a BaseImage object. If BaseImage object is provided, angle and scale are ignored. It can be a string orpathlib.Path
onPython 3+
- 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)
- scale_smooth (bool) – Scale is smoothed
- selectable (bool) – Image accepts user selection
- kwargs (dict, any) – Optional keyword arguments
Returns: Widget object
Return type:
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: Sound engine 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.
Note
Themes only modify visual behaviour of the Menu. For other options like rows/columns, enabling or disabling overflow, position or menu width/height see Menu parameters.
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, if user moves through nested submenus this buttons turns to a back-arrow
- scrollarea_outer_margin (tuple, list) – Outer scoll area margin (px), the tuple is added to computed scroll area width/height, it can add an margin to bottom/right scrolls after widgets. If value less than 1 use percentage of width/height. Default (0,0). It cannot be negative values
- 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 scrollbar shadow
- scrollbar_shadow_offset (int, float) – Offset of the scrollbar shadow
- scrollbar_shadow_position (str) – Position of the scrollbar shadow. See
pygame_menu.locals
- scrollbar_slider_color (tuple, list) – Color of the sliders
- scrollbar_slider_pad (int, float) – Space between slider and scrollbars borders
- scrollbar_thick (int, float) – Scrollbar thickness
- selection_color (tuple, list) – Color of the selected widget, it affects font color and the selection effect
- 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) – Title font color. If
None
use the widget font color - 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. See
pygame_menu.locals
- widget_alignment (str) – Widget default alignment
- widget_background_color (tuple, list,
pygame_menu.baseimage.BaseImage
, None) – Background color of a widget, it can be a color or a BaseImage object. Background fills the entire widget + the padding - widget_background_inflate (tuple, list) – Inflate background in (x,y) in px. By default it uses the highlight margin. This parameter is visual only. For modifying widget size use padding instead
- widget_font (str) – Widget font path or name
- widget_font_antialias (bool) – Widget font renders with antialiasing
- widget_font_background_color (tuple, list, None) – Widget font background color. By default it is None. If None the value will be the same as
background_color
if it’s is a color object and ifwidget_font_background_color_from_menu
is True andwidget_background_color
is None - widget_font_background_color_from_menu (bool) – Use menu background color as font background color. Disabled by default
- 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_padding (int, float, tuple, list) – Padding of the widget according to CSS rules. It can be a single digit, or a tuple of 2, 3, or 4 elements. Padding modifies widget width/height
- widget_offset (tuple, list) – (x, y) axis offset of widgets within Menu (px) respect to top-left corner. If value less than 1 use percentage of width/height. Default (0,0). It cannot be negative values
- widget_selection_effect (
pygame_menu.widgets.core.Selection
) – Widget selection effect object. This is visual-only, the selection properties does not affect widget height/width - widget_shadow (bool) – Indicate if the widget text shadow is enabled
- widget_shadow_color (tuple, list) – Color of the widget shadow
- widget_shadow_offset (int, float) – Offset of the widget shadow
- widget_shadow_position (str) – Position of shadow. See
pygame_menu.locals
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 / Examples¶
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
Other examples that show specific use cases of the menu are also provided:
$> python -m pygame_menu.examples.other.dynamic_button_append
$> python -m pygame_menu.examples.other.dynamic_widget_update
$> python -m pygame_menu.examples.other.image_background
Them can also be imported as follows:
from pygame_menu.examples.example import main
main()
Example sources can also be found in the Github repo.
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)
andMenu.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
, usewidth
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: Adds a function to the widget to be executed each time the widget is drawn.
The function that this method receives receives two objects: the widget itself and the menu reference.
import math def draw_update_function(widget, menu): t = widget.get_attribute('t', 0) t += menu.get_clock().get_time() widget.set_padding(10*(1 + math.sin(t)))) # Oscillating padding button = menu.add_button('This button updates its padding', None) button.set_draw_callback(draw_update_function)
After creating a new callback, this functions returns the ID of the call. It can be removed anytime using
widget.remove_draw_callback(id)
.Parameters: draw_callback (callable) – Function Returns: Callback ID Return type: str
Adds a function to the widget to be executed each time the widget is updated.
The function that this method receives receives two objects: the widget itself and the menu reference. It is similar to
add_draw_callback
.After creating a new callback, this functions returns the ID of the call. It can be removed anytime using
widget.remove_update_callback(id)
.Note
Not all widgets are updated, so the provided function may never be executed.
Parameters: update_callback (callable) – Function Returns: Callback ID Return type: str
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: Callback return value
Return type: any
Apply callbacks on widget draw.
Returns: None
Apply callbacks on widget update.
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: Callback return value
Return type: any
Change widget id.
Parameters: widget_id (str) – Widget ID 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
Expand background inflate to match the selection effect (the widget don’t require to be selected).
This is a permanent change; for dynamic purpuoses, depending if the widget is selected or not, setting
widget.selection_expand_background
toTrue
may help.Note
This method may have unexpected results with certain selection effects.
Returns: None
This method can flip the widget either vertically, horizontally, or both. Flipping a widget is non-destructive and does not change the dimensions.
Parameters: Returns: 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.
Dict values:
antialias
Font antialias (bool)background_color
Background color (tuple)color
Font color (tuple)name
Name of the font (str)selected_color
Selected color (tuple)size
Size of the font (int)
Returns: Dict Return type: dict
Return the widget height.
Warning
If the widget is not rendered, this method will return
0
.Parameters: Returns: Widget height (px)
Return type:
Return the widget ID.
Returns: Widget ID Return type: str
Return the widget margin.
Returns: Widget margin (left,bottom) Return type: tuple
Return the menu reference (if exists).
Warning
Use with caution.
Returns: Menu reference Return type: pygame_menu.Menu
, None
Return the widget padding.
Returns: Widget padding (top,right,bottom,left) Return type: tuple
Return the widget position tuple (x, y).
Returns: Widget position Return type: tuple
Return the Rect object, this forces the widget rendering.
Note
This is the only method that returns the rect with the padding applied. If widget._rect is used, the padding has not been applied.
Parameters: Returns: Widget rect
Return type:
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.
Warning
Use with caution.
Returns: Selection effect Return type: pygame_menu.widgets.core.Selection
Return the widget size.
Warning
If the widget is not rendered this method might return
(0,0)
.Parameters: Returns: Widget (width, height)
Return type:
Return widget surface.
Warning
Use with caution.
Returns: Widget surface Return type: pygame.Surface
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
Return the widget width.
Warning
If the widget is not rendered, this method will return
0
.Parameters: Returns: Widget width (px)
Return type:
Returns true if widget has the given attribute.
Parameters: key (str) – Key of the attribute Returns: True if exists Return type: bool
Hides widget.
Returns: None
Removes the given attribute from the widget. Throws
IndexError
if given key does not exist.Parameters: key (str) – Key of the attribute Returns: None
Removes draw callback from ID.
Parameters: callback_id (str) – Callback ID Returns: None
Removes update callback from ID.
Parameters: callback_id (str) – Callback ID Returns: None
Set the widget size to another size.
Note
This method calls
widget.scale
method; thus, some widgets may not support this transformation.Parameters: Returns: None
Unfiltered counterclockwise rotation. The angle argument represents degrees and can be any floating point value. Negative angle amounts will rotate clockwise.
Note
Not all widgets accepts rotation. Also this rotation only affects the text or images, the selection or background is not rotated.
Parameters: angle (int, float) – Rotation angle (degrees 0-360) Returns: None
Scale the widget to a desired width and height factor.
Note
Not all widgets are affected by scale.
Parameters: 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, None) – Inflate background in (x,y). If
None
, the widget value is not updated
Returns: None
- color (tuple, list,
Enable interfaces to control the widget.
Parameters: Returns: None
Set the text font.
Parameters: - font (str) – Font name (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, None) – Font background color
- antialias (bool) – Determines if antialias is applied to font (uses more processing power)
Returns: None
- font (str) – Font name (see
Set Widget margin (left, bottom).
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
, None) – Menu objectReturns: None
Set the Widget padding according to CSS rules.
- If an integer or float is provided: top, right, bottom and left values will be the same
- If 2-item tuple is provided: top and bottom takes the first value, left and right the second
- If 3-item tuple is provided: top will take the first value, left and right the second, and bottom the third
- If 4-item tuple is provided: padding will be (top, right, bottom, left)
Note
See CSS W3Schools for more info about padding.
Parameters: padding (int, float, tuple, list) – Can be a single number, or a tuple of 2, 3 or 4 elements following CSS style Returns: None
Set the widget 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 widget 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
Set widget visible.
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
Menu.update()
.Returns: True if the widget position has changed by events after the rendering. Return type: bool
Translate to (+x,+y) according to default position.
Note
To revert changes, only set to (0,0).
Parameters: Returns: None
Update internal variable according to the given events list and fire the callbacks.
Parameters: events (list[ pygame.event.Event
], tuple[pygame.event.Event
]) – List/Tuple of pygame eventsReturns: True if updated Return type: bool
Update function triggered by the button;
callback
cannot point to a Menu, that behaviour is only valid usingMenu.add_button()
method.Note
If button points to a submenu, and the callback is changed to a function, the submenu will be removed from the parent menu. Thus preserving the structure.
Parameters: - callback (callable) – Function
- args (any) – Arguments used by the function once triggered
Returns: None
Updates font. This method receives a style dict (non empty) containing the following keys:
antialias
Font antialias (bool)background_color
Background color (tuple)color
Font color (tuple)name
Name of the font (str)selected_color
Selected color (tuple)size
Size of the font (int)
Note
If a key is not defined it will be rewritten using current font style from
Widget.get_font_info()
method.Parameters: style (dict) – Font style dict Returns: None
ColorInput¶
Bases:
pygame_menu.widgets.widget.textinput.TextInput
Color input widget.
Note
This widget implements the same transformations as TextInput.
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 string drawn under the input
- cursor_color (tuple) – Color of cursor
- onchange (callable, None) – Function when changing the values of the color text
- onreturn (callable, None) – Function when pressing return on the color text input
- 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, any) – Optional keyword arguments
Adds a function to the widget to be executed each time the widget is drawn.
The function that this method receives receives two objects: the widget itself and the menu reference.
import math def draw_update_function(widget, menu): t = widget.get_attribute('t', 0) t += menu.get_clock().get_time() widget.set_padding(10*(1 + math.sin(t)))) # Oscillating padding button = menu.add_button('This button updates its padding', None) button.set_draw_callback(draw_update_function)
After creating a new callback, this functions returns the ID of the call. It can be removed anytime using
widget.remove_draw_callback(id)
.Parameters: draw_callback (callable) – Function Returns: Callback ID Return type: str
Adds a function to the widget to be executed each time the widget is updated.
The function that this method receives receives two objects: the widget itself and the menu reference. It is similar to
add_draw_callback
.After creating a new callback, this functions returns the ID of the call. It can be removed anytime using
widget.remove_update_callback(id)
.Note
Not all widgets are updated, so the provided function may never be executed.
Parameters: update_callback (callable) – Function Returns: Callback ID Return type: str
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: Callback return value
Return type: any
Apply callbacks on widget draw.
Returns: None
Apply callbacks on widget update.
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: Callback return value
Return type: any
Change widget id.
Parameters: widget_id (str) – Widget ID 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
Expand background inflate to match the selection effect (the widget don’t require to be selected).
This is a permanent change; for dynamic purpuoses, depending if the widget is selected or not, setting
widget.selection_expand_background
toTrue
may help.Note
This method may have unexpected results with certain selection effects.
Returns: None
This method can flip the widget either vertically, horizontally, or both. Flipping a widget is non-destructive and does not change the dimensions.
Parameters: Returns: 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.
Dict values:
antialias
Font antialias (bool)background_color
Background color (tuple)color
Font color (tuple)name
Name of the font (str)selected_color
Selected color (tuple)size
Size of the font (int)
Returns: Dict Return type: dict
Return the widget height.
Warning
If the widget is not rendered, this method will return
0
.Parameters: Returns: Widget height (px)
Return type:
Return the widget ID.
Returns: Widget ID Return type: str
Return the widget margin.
Returns: Widget margin (left,bottom) Return type: tuple
Return the menu reference (if exists).
Warning
Use with caution.
Returns: Menu reference Return type: pygame_menu.Menu
, None
Return the widget padding.
Returns: Widget padding (top,right,bottom,left) Return type: tuple
Return the widget position tuple (x, y).
Returns: Widget position Return type: tuple
Return the Rect object, this forces the widget rendering.
Note
This is the only method that returns the rect with the padding applied. If widget._rect is used, the padding has not been applied.
Parameters: Returns: Widget rect
Return type:
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.
Warning
Use with caution.
Returns: Selection effect Return type: pygame_menu.widgets.core.Selection
Return the widget size.
Warning
If the widget is not rendered this method might return
(0,0)
.Parameters: Returns: Widget (width, height)
Return type:
Return widget surface.
Warning
Use with caution.
Returns: Widget surface Return type: pygame.Surface
Return the widget title.
Returns: Widget title Return type: str
Return the color value as a tuple or red blue and green channels.
Note
If the data is invalid the widget returns (-1,-1,-1).
Returns: Color tuple as (R,G,B) Return type: tuple
Return the widget width.
Warning
If the widget is not rendered, this method will return
0
.Parameters: Returns: Widget width (px)
Return type:
Returns true if widget has the given attribute.
Parameters: key (str) – Key of the attribute Returns: True if exists Return type: bool
Hides widget.
Returns: None
Return true if the current value of the input is a valid color or not.
Returns: True if valid Return type: bool
Removes the given attribute from the widget. Throws
IndexError
if given key does not exist.Parameters: key (str) – Key of the attribute Returns: None
Removes draw callback from ID.
Parameters: callback_id (str) – Callback ID Returns: None
Removes update callback from ID.
Parameters: callback_id (str) – Callback ID Returns: None
Set the widget size to another size.
Note
This method calls
widget.scale
method; thus, some widgets may not support this transformation.Parameters: Returns: None
Unfiltered counterclockwise rotation. The angle argument represents degrees and can be any floating point value. Negative angle amounts will rotate clockwise.
Note
Not all widgets accepts rotation. Also this rotation only affects the text or images, the selection or background is not rotated.
Parameters: angle (int, float) – Rotation angle (degrees 0-360) Returns: None
Scale the widget to a desired width and height factor.
Note
Not all widgets are affected by scale.
Parameters: 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, None) – Inflate background in (x,y). If
None
, the widget value is not updated
Returns: None
- color (tuple, list,
Enable interfaces to control the widget.
Parameters: Returns: None
Set the text font.
Parameters: - font (str) – Font name (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, None) – Font background color
- antialias (bool) – Determines if antialias is applied to font (uses more processing power)
Returns: None
- font (str) – Font name (see
Set Widget margin (left, bottom).
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
, None) – Menu objectReturns: None
Set the Widget padding according to CSS rules.
- If an integer or float is provided: top, right, bottom and left values will be the same
- If 2-item tuple is provided: top and bottom takes the first value, left and right the second
- If 3-item tuple is provided: top will take the first value, left and right the second, and bottom the third
- If 4-item tuple is provided: padding will be (top, right, bottom, left)
Note
See CSS W3Schools for more info about padding.
Parameters: padding (int, float, tuple, list) – Can be a single number, or a tuple of 2, 3 or 4 elements following CSS style Returns: None
Set the widget 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 widget visible.
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
Menu.update()
.Returns: True if the widget position has changed by events after the rendering. Return type: bool
Translate to (+x,+y) according to default position.
Note
To revert changes, only set to (0,0).
Parameters: Returns: None
Update internal variable according to the given events list and fire the callbacks.
Parameters: events (list[ pygame.event.Event
], tuple[pygame.event.Event
]) – List/Tuple of pygame eventsReturns: True if updated Return type: bool
Updates font. This method receives a style dict (non empty) containing the following keys:
antialias
Font antialias (bool)background_color
Background color (tuple)color
Font color (tuple)name
Name of the font (str)selected_color
Selected color (tuple)size
Size of the font (int)
Note
If a key is not defined it will be rewritten using current font style from
Widget.get_font_info()
method.Parameters: style (dict) – Font style dict Returns: None
Image¶
Bases:
pygame_menu.widgets.core.widget.Widget
Image widget.
Parameters: - image_path (str,
pathlib.Path
, BaseImage) – Path of the image or BaseImage object. If BaseImage object is provided drawing mode is not considered. It can be a string orpathlib.Path
onPython 3+
- image_id (str) – Image ID
- angle (int, float) – Angle of the image in degrees (clockwise)
- scale (tuple, list) – Scale of the image (x,y)
- scale_smooth (bool) – Scale is smoothed
Adds a function to the widget to be executed each time the widget is drawn.
The function that this method receives receives two objects: the widget itself and the menu reference.
import math def draw_update_function(widget, menu): t = widget.get_attribute('t', 0) t += menu.get_clock().get_time() widget.set_padding(10*(1 + math.sin(t)))) # Oscillating padding button = menu.add_button('This button updates its padding', None) button.set_draw_callback(draw_update_function)
After creating a new callback, this functions returns the ID of the call. It can be removed anytime using
widget.remove_draw_callback(id)
.Parameters: draw_callback (callable) – Function Returns: Callback ID Return type: str
Adds a function to the widget to be executed each time the widget is updated.
The function that this method receives receives two objects: the widget itself and the menu reference. It is similar to
add_draw_callback
.After creating a new callback, this functions returns the ID of the call. It can be removed anytime using
widget.remove_update_callback(id)
.Note
Not all widgets are updated, so the provided function may never be executed.
Parameters: update_callback (callable) – Function Returns: Callback ID Return type: str
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: Callback return value
Return type: any
Apply callbacks on widget draw.
Returns: None
Apply callbacks on widget update.
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: Callback return value
Return type: any
Change widget id.
Parameters: widget_id (str) – Widget ID 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
Expand background inflate to match the selection effect (the widget don’t require to be selected).
This is a permanent change; for dynamic purpuoses, depending if the widget is selected or not, setting
widget.selection_expand_background
toTrue
may help.Note
This method may have unexpected results with certain selection effects.
Returns: None
This method can flip the widget either vertically, horizontally, or both. Flipping a widget is non-destructive and does not change the dimensions.
Parameters: Returns: 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.
Dict values:
antialias
Font antialias (bool)background_color
Background color (tuple)color
Font color (tuple)name
Name of the font (str)selected_color
Selected color (tuple)size
Size of the font (int)
Returns: Dict Return type: dict
Return the widget height.
Warning
If the widget is not rendered, this method will return
0
.Parameters: Returns: Widget height (px)
Return type:
Return the widget ID.
Returns: Widget ID Return type: str
Gets the BaseImage object from widget.
Returns: Widget image Return type: BaseImage
Return the widget margin.
Returns: Widget margin (left,bottom) Return type: tuple
Return the menu reference (if exists).
Warning
Use with caution.
Returns: Menu reference Return type: pygame_menu.Menu
, None
Return the widget padding.
Returns: Widget padding (top,right,bottom,left) Return type: tuple
Return the widget position tuple (x, y).
Returns: Widget position Return type: tuple
Return the Rect object, this forces the widget rendering.
Note
This is the only method that returns the rect with the padding applied. If widget._rect is used, the padding has not been applied.
Parameters: Returns: Widget rect
Return type:
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.
Warning
Use with caution.
Returns: Selection effect Return type: pygame_menu.widgets.core.Selection
Return the widget size.
Warning
If the widget is not rendered this method might return
(0,0)
.Parameters: Returns: Widget (width, height)
Return type:
Return widget surface.
Warning
Use with caution.
Returns: Widget surface Return type: pygame.Surface
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
Return the widget width.
Warning
If the widget is not rendered, this method will return
0
.Parameters: Returns: Widget width (px)
Return type:
Returns true if widget has the given attribute.
Parameters: key (str) – Key of the attribute Returns: True if exists Return type: bool
Hides widget.
Returns: None
Removes the given attribute from the widget. Throws
IndexError
if given key does not exist.Parameters: key (str) – Key of the attribute Returns: None
Removes draw callback from ID.
Parameters: callback_id (str) – Callback ID Returns: None
Removes update callback from ID.
Parameters: callback_id (str) – Callback ID Returns: None
Set the widget size to another size.
Note
This method calls
widget.scale
method; thus, some widgets may not support this transformation.Parameters: Returns: None
Unfiltered counterclockwise rotation. The angle argument represents degrees and can be any floating point value. Negative angle amounts will rotate clockwise.
Note
Not all widgets accepts rotation. Also this rotation only affects the text or images, the selection or background is not rotated.
Parameters: angle (int, float) – Rotation angle (degrees 0-360) Returns: None
Scale the widget to a desired width and height factor.
Note
Not all widgets are affected by scale.
Parameters: 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, None) – Inflate background in (x,y). If
None
, the widget value is not updated
Returns: None
- color (tuple, list,
Enable interfaces to control the widget.
Parameters: Returns: None
Set the text font.
Parameters: - font (str) – Font name (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, None) – Font background color
- antialias (bool) – Determines if antialias is applied to font (uses more processing power)
Returns: None
- font (str) – Font name (see
Set the BaseImage object from widget.
Parameters: image (BaseImage) – BaseImage object Returns: None
Set Widget margin (left, bottom).
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
, None) – Menu objectReturns: None
Set the Widget padding according to CSS rules.
- If an integer or float is provided: top, right, bottom and left values will be the same
- If 2-item tuple is provided: top and bottom takes the first value, left and right the second
- If 3-item tuple is provided: top will take the first value, left and right the second, and bottom the third
- If 4-item tuple is provided: padding will be (top, right, bottom, left)
Note
See CSS W3Schools for more info about padding.
Parameters: padding (int, float, tuple, list) – Can be a single number, or a tuple of 2, 3 or 4 elements following CSS style Returns: None
Set the widget 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 widget 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
Set widget visible.
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
Menu.update()
.Returns: True if the widget position has changed by events after the rendering. Return type: bool
Translate to (+x,+y) according to default position.
Note
To revert changes, only set to (0,0).
Parameters: Returns: None
Update internal variable according to the given events list and fire the callbacks.
Parameters: events (list[ pygame.event.Event
], tuple[pygame.event.Event
]) – List/Tuple of pygame eventsReturns: True if updated Return type: bool
Updates font. This method receives a style dict (non empty) containing the following keys:
antialias
Font antialias (bool)background_color
Background color (tuple)color
Font color (tuple)name
Name of the font (str)selected_color
Selected color (tuple)size
Size of the font (int)
Note
If a key is not defined it will be rewritten using current font style from
Widget.get_font_info()
method.Parameters: style (dict) – Font style dict Returns: None
- image_path (str,
Label¶
Bases:
pygame_menu.widgets.core.widget.Widget
Label widget.
Parameters: Adds a function to the widget to be executed each time the widget is drawn.
The function that this method receives receives two objects: the widget itself and the menu reference.
import math def draw_update_function(widget, menu): t = widget.get_attribute('t', 0) t += menu.get_clock().get_time() widget.set_padding(10*(1 + math.sin(t)))) # Oscillating padding button = menu.add_button('This button updates its padding', None) button.set_draw_callback(draw_update_function)
After creating a new callback, this functions returns the ID of the call. It can be removed anytime using
widget.remove_draw_callback(id)
.Parameters: draw_callback (callable) – Function Returns: Callback ID Return type: str
Adds a function to the widget to be executed each time the widget is updated.
The function that this method receives receives two objects: the widget itself and the menu reference. It is similar to
add_draw_callback
.After creating a new callback, this functions returns the ID of the call. It can be removed anytime using
widget.remove_update_callback(id)
.Note
Not all widgets are updated, so the provided function may never be executed.
Parameters: update_callback (callable) – Function Returns: Callback ID Return type: str
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: Callback return value
Return type: any
Apply callbacks on widget draw.
Returns: None
Apply callbacks on widget update.
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: Callback return value
Return type: any
Change widget id.
Parameters: widget_id (str) – Widget ID 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
Expand background inflate to match the selection effect (the widget don’t require to be selected).
This is a permanent change; for dynamic purpuoses, depending if the widget is selected or not, setting
widget.selection_expand_background
toTrue
may help.Note
This method may have unexpected results with certain selection effects.
Returns: None
This method can flip the widget either vertically, horizontally, or both. Flipping a widget is non-destructive and does not change the dimensions.
Parameters: Returns: 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.
Dict values:
antialias
Font antialias (bool)background_color
Background color (tuple)color
Font color (tuple)name
Name of the font (str)selected_color
Selected color (tuple)size
Size of the font (int)
Returns: Dict Return type: dict
Return the widget height.
Warning
If the widget is not rendered, this method will return
0
.Parameters: Returns: Widget height (px)
Return type:
Return the widget ID.
Returns: Widget ID Return type: str
Return the widget margin.
Returns: Widget margin (left,bottom) Return type: tuple
Return the menu reference (if exists).
Warning
Use with caution.
Returns: Menu reference Return type: pygame_menu.Menu
, None
Return the widget padding.
Returns: Widget padding (top,right,bottom,left) Return type: tuple
Return the widget position tuple (x, y).
Returns: Widget position Return type: tuple
Return the Rect object, this forces the widget rendering.
Note
This is the only method that returns the rect with the padding applied. If widget._rect is used, the padding has not been applied.
Parameters: Returns: Widget rect
Return type:
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.
Warning
Use with caution.
Returns: Selection effect Return type: pygame_menu.widgets.core.Selection
Return the widget size.
Warning
If the widget is not rendered this method might return
(0,0)
.Parameters: Returns: Widget (width, height)
Return type:
Return widget surface.
Warning
Use with caution.
Returns: Widget surface Return type: pygame.Surface
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
Return the widget width.
Warning
If the widget is not rendered, this method will return
0
.Parameters: Returns: Widget width (px)
Return type:
Returns true if widget has the given attribute.
Parameters: key (str) – Key of the attribute Returns: True if exists Return type: bool
Hides widget.
Returns: None
Removes the given attribute from the widget. Throws
IndexError
if given key does not exist.Parameters: key (str) – Key of the attribute Returns: None
Removes draw callback from ID.
Parameters: callback_id (str) – Callback ID Returns: None
Removes update callback from ID.
Parameters: callback_id (str) – Callback ID Returns: None
Set the widget size to another size.
Note
This method calls
widget.scale
method; thus, some widgets may not support this transformation.Parameters: Returns: None
Unfiltered counterclockwise rotation. The angle argument represents degrees and can be any floating point value. Negative angle amounts will rotate clockwise.
Note
Not all widgets accepts rotation. Also this rotation only affects the text or images, the selection or background is not rotated.
Parameters: angle (int, float) – Rotation angle (degrees 0-360) Returns: None
Scale the widget to a desired width and height factor.
Note
Not all widgets are affected by scale.
Parameters: 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, None) – Inflate background in (x,y). If
None
, the widget value is not updated
Returns: None
- color (tuple, list,
Enable interfaces to control the widget.
Parameters: Returns: None
Set the text font.
Parameters: - font (str) – Font name (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, None) – Font background color
- antialias (bool) – Determines if antialias is applied to font (uses more processing power)
Returns: None
- font (str) – Font name (see
Set Widget margin (left, bottom).
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
, None) – Menu objectReturns: None
Set the Widget padding according to CSS rules.
- If an integer or float is provided: top, right, bottom and left values will be the same
- If 2-item tuple is provided: top and bottom takes the first value, left and right the second
- If 3-item tuple is provided: top will take the first value, left and right the second, and bottom the third
- If 4-item tuple is provided: padding will be (top, right, bottom, left)
Note
See CSS W3Schools for more info about padding.
Parameters: padding (int, float, tuple, list) – Can be a single number, or a tuple of 2, 3 or 4 elements following CSS style Returns: None
Set the widget 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 widget 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
Set widget visible.
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
Menu.update()
.Returns: True if the widget position has changed by events after the rendering. Return type: bool
Translate to (+x,+y) according to default position.
Note
To revert changes, only set to (0,0).
Parameters: Returns: None
Update internal variable according to the given events list and fire the callbacks.
Parameters: events (list[ pygame.event.Event
], tuple[pygame.event.Event
]) – List/Tuple of pygame eventsReturns: True if updated Return type: bool
Updates font. This method receives a style dict (non empty) containing the following keys:
antialias
Font antialias (bool)background_color
Background color (tuple)color
Font color (tuple)name
Name of the font (str)selected_color
Selected color (tuple)size
Size of the font (int)
Note
If a key is not defined it will be rewritten using current font style from
Widget.get_font_info()
method.Parameters: style (dict) – Font style dict Returns: None
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.
Note
This widget only accepts translation transformation.
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 pressing and moving the scroll
Adds a function to the widget to be executed each time the widget is drawn.
The function that this method receives receives two objects: the widget itself and the menu reference.
import math def draw_update_function(widget, menu): t = widget.get_attribute('t', 0) t += menu.get_clock().get_time() widget.set_padding(10*(1 + math.sin(t)))) # Oscillating padding button = menu.add_button('This button updates its padding', None) button.set_draw_callback(draw_update_function)
After creating a new callback, this functions returns the ID of the call. It can be removed anytime using
widget.remove_draw_callback(id)
.Parameters: draw_callback (callable) – Function Returns: Callback ID Return type: str
Adds a function to the widget to be executed each time the widget is updated.
The function that this method receives receives two objects: the widget itself and the menu reference. It is similar to
add_draw_callback
.After creating a new callback, this functions returns the ID of the call. It can be removed anytime using
widget.remove_update_callback(id)
.Note
Not all widgets are updated, so the provided function may never be executed.
Parameters: update_callback (callable) – Function Returns: Callback ID Return type: str
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: Callback return value
Return type: any
Apply callbacks on widget draw.
Returns: None
Apply callbacks on widget update.
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: Callback return value
Return type: any
Change widget id.
Parameters: widget_id (str) – Widget ID 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
Expand background inflate to match the selection effect (the widget don’t require to be selected).
This is a permanent change; for dynamic purpuoses, depending if the widget is selected or not, setting
widget.selection_expand_background
toTrue
may help.Note
This method may have unexpected results with certain selection effects.
Returns: None
This method can flip the widget either vertically, horizontally, or both. Flipping a widget is non-destructive and does not change the dimensions.
Parameters: Returns: 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.
Dict values:
antialias
Font antialias (bool)background_color
Background color (tuple)color
Font color (tuple)name
Name of the font (str)selected_color
Selected color (tuple)size
Size of the font (int)
Returns: Dict Return type: dict
Return the widget height.
Warning
If the widget is not rendered, this method will return
0
.Parameters: Returns: Widget height (px)
Return type:
Return the widget ID.
Returns: Widget ID Return type: str
Return the widget margin.
Returns: Widget margin (left,bottom) Return type: tuple
Return the greatest acceptable value.
Returns: Greatest acceptable value Return type: int
Return the menu reference (if exists).
Warning
Use with caution.
Returns: Menu reference Return type: pygame_menu.Menu
, None
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 the widget padding.
Returns: Widget padding (top,right,bottom,left) Return type: tuple
Return amount that the value changes by when the user click on the page control surface.
Returns: Page step Return type: int
Return the widget position tuple (x, y).
Returns: Widget position Return type: tuple
Return the Rect object, this forces the widget rendering.
Note
This is the only method that returns the rect with the padding applied. If widget._rect is used, the padding has not been applied.
Parameters: Returns: Widget rect
Return type:
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.
Warning
Use with caution.
Returns: Selection effect Return type: pygame_menu.widgets.core.Selection
Return the widget size.
Warning
If the widget is not rendered this method might return
(0,0)
.Parameters: Returns: Widget (width, height)
Return type:
Return widget surface.
Warning
Use with caution.
Returns: Widget surface Return type: pygame.Surface
Return the thickness of the bar.
Returns: Thickness (px) Return type: int
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
Return the widget width.
Warning
If the widget is not rendered, this method will return
0
.Parameters: Returns: Widget width (px)
Return type:
Returns true if widget has the given attribute.
Parameters: key (str) – Key of the attribute Returns: True if exists Return type: bool
Hides widget.
Returns: None
Removes the given attribute from the widget. Throws
IndexError
if given key does not exist.Parameters: key (str) – Key of the attribute Returns: None
Removes draw callback from ID.
Parameters: callback_id (str) – Callback ID Returns: None
Removes update callback from ID.
Parameters: callback_id (str) – Callback ID Returns: None
Set the widget size to another size.
Note
This method calls
widget.scale
method; thus, some widgets may not support this transformation.Parameters: Returns: None
Unfiltered counterclockwise rotation. The angle argument represents degrees and can be any floating point value. Negative angle amounts will rotate clockwise.
Note
Not all widgets accepts rotation. Also this rotation only affects the text or images, the selection or background is not rotated.
Parameters: angle (int, float) – Rotation angle (degrees 0-360) Returns: None
Scale the widget to a desired width and height factor.
Note
Not all widgets are affected by scale.
Parameters: 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, None) – Inflate background in (x,y). If
None
, the widget value is not updated
Returns: None
- color (tuple, list,
Enable interfaces to control the widget.
Parameters: Returns: None
Set the text font.
Parameters: - font (str) – Font name (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, None) – Font background color
- antialias (bool) – Determines if antialias is applied to font (uses more processing power)
Returns: None
- font (str) – Font name (see
Set the length of the page control area.
Parameters: value (int, float) – Length of the area Returns: None
Set Widget margin (left, bottom).
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
, None) – 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 Widget padding according to CSS rules.
- If an integer or float is provided: top, right, bottom and left values will be the same
- If 2-item tuple is provided: top and bottom takes the first value, left and right the second
- If 3-item tuple is provided: top will take the first value, left and right the second, and bottom the third
- If 4-item tuple is provided: padding will be (top, right, bottom, left)
Note
See CSS W3Schools for more info about padding.
Parameters: padding (int, float, tuple, list) – Can be a single number, or a tuple of 2, 3 or 4 elements following CSS style Returns: None
Set the amount that the value changes by when the user click on the page control surface.
Note
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 widget 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 widget visible.
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
Menu.update()
.Returns: True if the widget position has changed by events after the rendering. Return type: bool
Translate to (+x,+y) according to default position.
Note
To revert changes, only set to (0,0).
Parameters: Returns: None
Update internal variable according to the given events list and fire the callbacks.
Parameters: events (list[ pygame.event.Event
], tuple[pygame.event.Event
]) – List/Tuple of pygame eventsReturns: True if updated Return type: bool
Updates font. This method receives a style dict (non empty) containing the following keys:
antialias
Font antialias (bool)background_color
Background color (tuple)color
Font color (tuple)name
Name of the font (str)selected_color
Selected color (tuple)size
Size of the font (int)
Note
If a key is not defined it will be rewritten using current font style from
Widget.get_font_info()
method.Parameters: style (dict) – Font style dict Returns: None
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 on the selector
- kwargs (dict, any) – Optional keyword arguments
Adds a function to the widget to be executed each time the widget is drawn.
The function that this method receives receives two objects: the widget itself and the menu reference.
import math def draw_update_function(widget, menu): t = widget.get_attribute('t', 0) t += menu.get_clock().get_time() widget.set_padding(10*(1 + math.sin(t)))) # Oscillating padding button = menu.add_button('This button updates its padding', None) button.set_draw_callback(draw_update_function)
After creating a new callback, this functions returns the ID of the call. It can be removed anytime using
widget.remove_draw_callback(id)
.Parameters: draw_callback (callable) – Function Returns: Callback ID Return type: str
Adds a function to the widget to be executed each time the widget is updated.
The function that this method receives receives two objects: the widget itself and the menu reference. It is similar to
add_draw_callback
.After creating a new callback, this functions returns the ID of the call. It can be removed anytime using
widget.remove_update_callback(id)
.Note
Not all widgets are updated, so the provided function may never be executed.
Parameters: update_callback (callable) – Function Returns: Callback ID Return type: str
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: Callback return value
Return type: any
Apply callbacks on widget draw.
Returns: None
Apply callbacks on widget update.
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: Callback return value
Return type: any
Change widget id.
Parameters: widget_id (str) – Widget ID 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
Expand background inflate to match the selection effect (the widget don’t require to be selected).
This is a permanent change; for dynamic purpuoses, depending if the widget is selected or not, setting
widget.selection_expand_background
toTrue
may help.Note
This method may have unexpected results with certain selection effects.
Returns: None
This method can flip the widget either vertically, horizontally, or both. Flipping a widget is non-destructive and does not change the dimensions.
Parameters: Returns: 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.
Dict values:
antialias
Font antialias (bool)background_color
Background color (tuple)color
Font color (tuple)name
Name of the font (str)selected_color
Selected color (tuple)size
Size of the font (int)
Returns: Dict Return type: dict
Return the widget height.
Warning
If the widget is not rendered, this method will return
0
.Parameters: Returns: Widget height (px)
Return type:
Return the widget ID.
Returns: Widget ID Return type: str
Return the widget margin.
Returns: Widget margin (left,bottom) Return type: tuple
Return the menu reference (if exists).
Warning
Use with caution.
Returns: Menu reference Return type: pygame_menu.Menu
, None
Return the widget padding.
Returns: Widget padding (top,right,bottom,left) Return type: tuple
Return the widget position tuple (x, y).
Returns: Widget position Return type: tuple
Return the Rect object, this forces the widget rendering.
Note
This is the only method that returns the rect with the padding applied. If widget._rect is used, the padding has not been applied.
Parameters: Returns: Widget rect
Return type:
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.
Warning
Use with caution.
Returns: Selection effect Return type: pygame_menu.widgets.core.Selection
Return the widget size.
Warning
If the widget is not rendered this method might return
(0,0)
.Parameters: Returns: Widget (width, height)
Return type:
Return widget surface.
Warning
Use with caution.
Returns: Widget surface Return type: pygame.Surface
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
Return the widget width.
Warning
If the widget is not rendered, this method will return
0
.Parameters: Returns: Widget width (px)
Return type:
Returns true if widget has the given attribute.
Parameters: key (str) – Key of the attribute Returns: True if exists Return type: bool
Hides widget.
Returns: None
Move selector to left.
Returns: None
Removes the given attribute from the widget. Throws
IndexError
if given key does not exist.Parameters: key (str) – Key of the attribute Returns: None
Removes draw callback from ID.
Parameters: callback_id (str) – Callback ID Returns: None
Removes update callback from ID.
Parameters: callback_id (str) – Callback ID Returns: None
Set the widget size to another size.
Note
This method calls
widget.scale
method; thus, some widgets may not support this transformation.Parameters: Returns: None
Move selector to right.
Returns: None
Unfiltered counterclockwise rotation. The angle argument represents degrees and can be any floating point value. Negative angle amounts will rotate clockwise.
Note
Not all widgets accepts rotation. Also this rotation only affects the text or images, the selection or background is not rotated.
Parameters: angle (int, float) – Rotation angle (degrees 0-360) Returns: None
Scale the widget to a desired width and height factor.
Note
Not all widgets are affected by scale.
Parameters: 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, None) – Inflate background in (x,y). If
None
, the widget value is not updated
Returns: None
- color (tuple, list,
Enable interfaces to control the widget.
Parameters: Returns: None
Set the text font.
Parameters: - font (str) – Font name (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, None) – Font background color
- antialias (bool) – Determines if antialias is applied to font (uses more processing power)
Returns: None
- font (str) – Font name (see
Set Widget margin (left, bottom).
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
, None) – Menu objectReturns: None
Set the Widget padding according to CSS rules.
- If an integer or float is provided: top, right, bottom and left values will be the same
- If 2-item tuple is provided: top and bottom takes the first value, left and right the second
- If 3-item tuple is provided: top will take the first value, left and right the second, and bottom the third
- If 4-item tuple is provided: padding will be (top, right, bottom, left)
Note
See CSS W3Schools for more info about padding.
Parameters: padding (int, float, tuple, list) – Can be a single number, or a tuple of 2, 3 or 4 elements following CSS style Returns: None
Set the widget 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. This method raises
ValueError
if no element found.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
Set widget visible.
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
Menu.update()
.Returns: True if the widget position has changed by events after the rendering. Return type: bool
Translate to (+x,+y) according to default position.
Note
To revert changes, only set to (0,0).
Parameters: Returns: None
Update internal variable according to the given events list and fire the callbacks.
Parameters: events (list[ pygame.event.Event
], tuple[pygame.event.Event
]) – List/Tuple of pygame eventsReturns: True if updated Return type: bool
Update selector elements.
Parameters: elements (Object) – Elements of the selector Returns: None
Updates font. This method receives a style dict (non empty) containing the following keys:
antialias
Font antialias (bool)background_color
Background color (tuple)color
Font color (tuple)name
Name of the font (str)selected_color
Selected color (tuple)size
Size of the font (int)
Note
If a key is not defined it will be rewritten using current font style from
Widget.get_font_info()
method.Parameters: style (dict) – Font style dict Returns: None
TextInput¶
Bases:
pygame_menu.widgets.core.widget.Widget
Text input widget.
Note
This widget only accepts vertical flip and translation transformations.
Parameters: - title (str) – Text input title
- textinput_id (str) – ID of the text input
- input_type (str) – Type of data
- input_underline (str) – Character string drawn under the input
- input_underline_len (int) – Total of characters to be drawn under the input. If 0 this number is computed automatically to fit the font
- 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 text input
- onreturn (callable, None) – Callback when pressing return on the text input
- 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
- repeat_touch_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, any) – Optional keyword arguments
Adds a function to the widget to be executed each time the widget is drawn.
The function that this method receives receives two objects: the widget itself and the menu reference.
import math def draw_update_function(widget, menu): t = widget.get_attribute('t', 0) t += menu.get_clock().get_time() widget.set_padding(10*(1 + math.sin(t)))) # Oscillating padding button = menu.add_button('This button updates its padding', None) button.set_draw_callback(draw_update_function)
After creating a new callback, this functions returns the ID of the call. It can be removed anytime using
widget.remove_draw_callback(id)
.Parameters: draw_callback (callable) – Function Returns: Callback ID Return type: str
Adds a function to the widget to be executed each time the widget is updated.
The function that this method receives receives two objects: the widget itself and the menu reference. It is similar to
add_draw_callback
.After creating a new callback, this functions returns the ID of the call. It can be removed anytime using
widget.remove_update_callback(id)
.Note
Not all widgets are updated, so the provided function may never be executed.
Parameters: update_callback (callable) – Function Returns: Callback ID Return type: str
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: Callback return value
Return type: any
Apply callbacks on widget draw.
Returns: None
Apply callbacks on widget update.
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: Callback return value
Return type: any
Change widget id.
Parameters: widget_id (str) – Widget ID 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
Expand background inflate to match the selection effect (the widget don’t require to be selected).
This is a permanent change; for dynamic purpuoses, depending if the widget is selected or not, setting
widget.selection_expand_background
toTrue
may help.Note
This method may have unexpected results with certain selection effects.
Returns: None
This method can flip the widget either vertically, horizontally, or both. Flipping a widget is non-destructive and does not change the dimensions.
Parameters: Returns: 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.
Dict values:
antialias
Font antialias (bool)background_color
Background color (tuple)color
Font color (tuple)name
Name of the font (str)selected_color
Selected color (tuple)size
Size of the font (int)
Returns: Dict Return type: dict
Return the widget height.
Warning
If the widget is not rendered, this method will return
0
.Parameters: Returns: Widget height (px)
Return type:
Return the widget ID.
Returns: Widget ID Return type: str
Return the widget margin.
Returns: Widget margin (left,bottom) Return type: tuple
Return the menu reference (if exists).
Warning
Use with caution.
Returns: Menu reference Return type: pygame_menu.Menu
, None
Return the widget padding.
Returns: Widget padding (top,right,bottom,left) Return type: tuple
Return the widget position tuple (x, y).
Returns: Widget position Return type: tuple
Return the Rect object, this forces the widget rendering.
Note
This is the only method that returns the rect with the padding applied. If widget._rect is used, the padding has not been applied.
Parameters: Returns: Widget rect
Return type:
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.
Warning
Use with caution.
Returns: Selection effect Return type: pygame_menu.widgets.core.Selection
Return the widget size.
Warning
If the widget is not rendered this method might return
(0,0)
.Parameters: Returns: Widget (width, height)
Return type:
Return widget surface.
Warning
Use with caution.
Returns: Widget surface Return type: pygame.Surface
Return the widget title.
Returns: Widget title Return type: str
Return the value of the text.
Returns: Text inside the widget Return type: str
Return the widget width.
Warning
If the widget is not rendered, this method will return
0
.Parameters: Returns: Widget width (px)
Return type:
Returns true if widget has the given attribute.
Parameters: key (str) – Key of the attribute Returns: True if exists Return type: bool
Hides widget.
Returns: None
Removes the given attribute from the widget. Throws
IndexError
if given key does not exist.Parameters: key (str) – Key of the attribute Returns: None
Removes draw callback from ID.
Parameters: callback_id (str) – Callback ID Returns: None
Removes update callback from ID.
Parameters: callback_id (str) – Callback ID Returns: None
Set the widget size to another size.
Note
This method calls
widget.scale
method; thus, some widgets may not support this transformation.Parameters: Returns: None
Unfiltered counterclockwise rotation. The angle argument represents degrees and can be any floating point value. Negative angle amounts will rotate clockwise.
Note
Not all widgets accepts rotation. Also this rotation only affects the text or images, the selection or background is not rotated.
Parameters: angle (int, float) – Rotation angle (degrees 0-360) Returns: None
Scale the widget to a desired width and height factor.
Note
Not all widgets are affected by scale.
Parameters: 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, None) – Inflate background in (x,y). If
None
, the widget value is not updated
Returns: None
- color (tuple, list,
Enable interfaces to control the widget.
Parameters: Returns: None
Set the text font.
Parameters: - font (str) – Font name (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, None) – Font background color
- antialias (bool) – Determines if antialias is applied to font (uses more processing power)
Returns: None
- font (str) – Font name (see
Set Widget margin (left, bottom).
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
, None) – Menu objectReturns: None
Set the Widget padding according to CSS rules.
- If an integer or float is provided: top, right, bottom and left values will be the same
- If 2-item tuple is provided: top and bottom takes the first value, left and right the second
- If 3-item tuple is provided: top will take the first value, left and right the second, and bottom the third
- If 4-item tuple is provided: padding will be (top, right, bottom, left)
Note
See CSS W3Schools for more info about padding.
Parameters: padding (int, float, tuple, list) – Can be a single number, or a tuple of 2, 3 or 4 elements following CSS style Returns: None
Set the widget 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 widget visible.
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
Menu.update()
.Returns: True if the widget position has changed by events after the rendering. Return type: bool
Translate to (+x,+y) according to default position.
Note
To revert changes, only set to (0,0).
Parameters: Returns: None
Update internal variable according to the given events list and fire the callbacks.
Parameters: events (list[ pygame.event.Event
], tuple[pygame.event.Event
]) – List/Tuple of pygame eventsReturns: True if updated Return type: bool
Updates font. This method receives a style dict (non empty) containing the following keys:
antialias
Font antialias (bool)background_color
Background color (tuple)color
Font color (tuple)name
Name of the font (str)selected_color
Selected color (tuple)size
Size of the font (int)
Note
If a key is not defined it will be rewritten using current font style from
Widget.get_font_info()
method.Parameters: style (dict) – Font style dict Returns: None
VMargin¶
Bases:
pygame_menu.widgets.core.widget.Widget
Vertical margin widget.
Note
This widget does not implement any transformation.
Parameters: widget_id (str) – ID of the widget Adds a function to the widget to be executed each time the widget is drawn.
The function that this method receives receives two objects: the widget itself and the menu reference.
import math def draw_update_function(widget, menu): t = widget.get_attribute('t', 0) t += menu.get_clock().get_time() widget.set_padding(10*(1 + math.sin(t)))) # Oscillating padding button = menu.add_button('This button updates its padding', None) button.set_draw_callback(draw_update_function)
After creating a new callback, this functions returns the ID of the call. It can be removed anytime using
widget.remove_draw_callback(id)
.Parameters: draw_callback (callable) – Function Returns: Callback ID Return type: str
Adds a function to the widget to be executed each time the widget is updated.
The function that this method receives receives two objects: the widget itself and the menu reference. It is similar to
add_draw_callback
.After creating a new callback, this functions returns the ID of the call. It can be removed anytime using
widget.remove_update_callback(id)
.Note
Not all widgets are updated, so the provided function may never be executed.
Parameters: update_callback (callable) – Function Returns: Callback ID Return type: str
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: Callback return value
Return type: any
Apply callbacks on widget draw.
Returns: None
Apply callbacks on widget update.
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: Callback return value
Return type: any
Change widget id.
Parameters: widget_id (str) – Widget ID 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
Expand background inflate to match the selection effect (the widget don’t require to be selected).
This is a permanent change; for dynamic purpuoses, depending if the widget is selected or not, setting
widget.selection_expand_background
toTrue
may help.Note
This method may have unexpected results with certain selection effects.
Returns: None
This method can flip the widget either vertically, horizontally, or both. Flipping a widget is non-destructive and does not change the dimensions.
Parameters: Returns: 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.
Dict values:
antialias
Font antialias (bool)background_color
Background color (tuple)color
Font color (tuple)name
Name of the font (str)selected_color
Selected color (tuple)size
Size of the font (int)
Returns: Dict Return type: dict
Return the widget height.
Warning
If the widget is not rendered, this method will return
0
.Parameters: Returns: Widget height (px)
Return type:
Return the widget ID.
Returns: Widget ID Return type: str
Return the widget margin.
Returns: Widget margin (left,bottom) Return type: tuple
Return the menu reference (if exists).
Warning
Use with caution.
Returns: Menu reference Return type: pygame_menu.Menu
, None
Return the widget padding.
Returns: Widget padding (top,right,bottom,left) Return type: tuple
Return the widget position tuple (x, y).
Returns: Widget position Return type: tuple
Return the Rect object, this forces the widget rendering.
Note
This is the only method that returns the rect with the padding applied. If widget._rect is used, the padding has not been applied.
Parameters: Returns: Widget rect
Return type:
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.
Warning
Use with caution.
Returns: Selection effect Return type: pygame_menu.widgets.core.Selection
Return the widget size.
Warning
If the widget is not rendered this method might return
(0,0)
.Parameters: Returns: Widget (width, height)
Return type:
Return widget surface.
Warning
Use with caution.
Returns: Widget surface Return type: pygame.Surface
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
Return the widget width.
Warning
If the widget is not rendered, this method will return
0
.Parameters: Returns: Widget width (px)
Return type:
Returns true if widget has the given attribute.
Parameters: key (str) – Key of the attribute Returns: True if exists Return type: bool
Hides widget.
Returns: None
Removes the given attribute from the widget. Throws
IndexError
if given key does not exist.Parameters: key (str) – Key of the attribute Returns: None
Removes draw callback from ID.
Parameters: callback_id (str) – Callback ID Returns: None
Removes update callback from ID.
Parameters: callback_id (str) – Callback ID Returns: None
Set the widget size to another size.
Note
This method calls
widget.scale
method; thus, some widgets may not support this transformation.Parameters: Returns: None
Unfiltered counterclockwise rotation. The angle argument represents degrees and can be any floating point value. Negative angle amounts will rotate clockwise.
Note
Not all widgets accepts rotation. Also this rotation only affects the text or images, the selection or background is not rotated.
Parameters: angle (int, float) – Rotation angle (degrees 0-360) Returns: None
Scale the widget to a desired width and height factor.
Note
Not all widgets are affected by scale.
Parameters: 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, None) – Inflate background in (x,y). If
None
, the widget value is not updated
Returns: None
- color (tuple, list,
Enable interfaces to control the widget.
Parameters: Returns: None
Set the text font.
Parameters: - font (str) – Font name (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, None) – Font background color
- antialias (bool) – Determines if antialias is applied to font (uses more processing power)
Returns: None
- font (str) – Font name (see
Set Widget margin (left, bottom).
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
, None) – Menu objectReturns: None
Set the Widget padding according to CSS rules.
- If an integer or float is provided: top, right, bottom and left values will be the same
- If 2-item tuple is provided: top and bottom takes the first value, left and right the second
- If 3-item tuple is provided: top will take the first value, left and right the second, and bottom the third
- If 4-item tuple is provided: padding will be (top, right, bottom, left)
Note
See CSS W3Schools for more info about padding.
Parameters: padding (int, float, tuple, list) – Can be a single number, or a tuple of 2, 3 or 4 elements following CSS style Returns: None
Set the widget 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 widget 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
Set widget visible.
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
Menu.update()
.Returns: True if the widget position has changed by events after the rendering. Return type: bool
Translate to (+x,+y) according to default position.
Note
To revert changes, only set to (0,0).
Parameters: Returns: None
Update internal variable according to the given events list and fire the callbacks.
Parameters: events (list[ pygame.event.Event
], tuple[pygame.event.Event
]) – List/Tuple of pygame eventsReturns: True if updated Return type: bool
Updates font. This method receives a style dict (non empty) containing the following keys:
antialias
Font antialias (bool)background_color
Background color (tuple)color
Font color (tuple)name
Name of the font (str)selected_color
Selected color (tuple)size
Size of the font (int)
Note
If a key is not defined it will be rewritten using current font style from
Widget.get_font_info()
method.Parameters: style (dict) – Font style dict Returns: None