pygame_gui package

Subpackages

Submodules

pygame_gui.ui_manager module

class pygame_gui.ui_manager.UIManager(window_resolution: Tuple[int, int], theme_path: Union[str, pygame_gui.core.utility.PackageResource, None] = None, enable_live_theme_updates: bool = True, resource_loader: Optional[pygame_gui.core.resource_loaders.IResourceLoader] = None, starting_language: str = 'en', translation_directory_paths: Optional[List[str]] = None)

Bases: pygame_gui.core.interfaces.manager_interface.IUIManagerInterface

The UI Manager class helps keep track of all the moving parts in the pygame_gui system.

Before doing anything else with pygame_gui create a UIManager and remember to update it every frame.

Parameters:
  • window_resolution -- window resolution.
  • theme_path -- relative file path to theme.
  • enable_live_theme_updates -- Lets the theme update in-game after we edit the theme file
add_font_paths(font_name: str, regular_path: str, bold_path: str = None, italic_path: str = None, bold_italic_path: str = None)

Add file paths for custom fonts you want to use in the UI. For each font name you add you can specify font files for different styles. Fonts with designed styles tend to render a lot better than fonts that are forced to make use of pygame's bold and italic styling effects, so if you plan to use bold and italic text at small sizes - find fonts with these styles available as separate files.

The font name you specify here can be used to choose the font in the blocks of HTML-subset formatted text, available in some of the UI elements like the UITextBox.

It is recommended that you also pre-load any fonts you use at an appropriate moment in your project rather than letting the library dynamically load them when they are required. That is because dynamic loading of large font files can cause UI elements with a lot of font usage to appear rather slowly as they are waiting for the fonts they need to load.

Parameters:
  • font_name -- The name of the font that will be used to reference it elsewhere in the GUI.
  • regular_path -- The path of the font file for this font with no styles applied.
  • bold_path -- The path of the font file for this font with just bold style applied.
  • italic_path -- The path of the font file for this font with just italic style applied.
  • bold_italic_path -- The path of the font file for this font with bold & italic style applied.
calculate_scaled_mouse_position(position: Tuple[int, int]) → Tuple[int, int]

Scaling an input mouse position by a scale factor.

clear_and_reset()

Clear all existing windows and the root container, which should get rid of all created UI elements. We then recreate the UIWindowStack and the root container.

create_tool_tip(text: str, position: Tuple[int, int], hover_distance: Tuple[int, int], parent_element: pygame_gui.core.interfaces.element_interface.IUIElementInterface, object_id: pygame_gui.core.object_id.ObjectID, *, wrap_width: Optional[int] = None, text_kwargs: Optional[Dict[str, str]] = None) → pygame_gui.core.interfaces.tool_tip_interface.IUITooltipInterface

Creates a tool tip ands returns it. Have hidden this away in the manager so we can call it from other UI elements and create tool tips without creating cyclical import problems.

Parameters:
  • text -- The tool tips text, can utilise the HTML subset used in all UITextBoxes.
  • position -- The screen position to create the tool tip for.
  • hover_distance -- The distance we should hover away from our target position.
  • parent_element -- The UIElement that spawned this tool tip.
  • object_id -- the object_id of the tooltip.
  • wrap_width -- an optional width for the tool tip, will overwrite any value from the theme file.
  • text_kwargs -- a dictionary of variable arguments to pass to the translated string useful when you have multiple translations that need variables inserted in the middle.
Returns:

A tool tip placed somewhere on the screen.

draw_ui(window_surface: pygame.surface.Surface)

Draws all the UI elements on the screen. Generally you want this to be after the rest of your game sprites have been drawn.

If you want to do something particularly unusual with drawing you may have to write your own UI manager.

Parameters:window_surface -- The screen or window surface on which we are going to draw all of our UI Elements.
get_double_click_time() → float

Returns time between clicks that counts as a double click.

Returns:A float, time measured in seconds.
get_focus_set()

Gets the focused set.

Returns:The set of elements that currently have interactive focus. If None, nothing is currently focused.
get_hovering_any_element() → bool

True if any UI element (other than the root container) is hovered by the mouse.

Combined with 'get_focus_set()' and the return value from process_events(), it should make it easier to switch input events between the UI and other parts of an application.

get_locale()

Get the locale language code being used in the UIManager

Returns:A two letter ISO 639-1 code for the current locale.
get_mouse_position() → Tuple[int, int]

Wrapping pygame mouse position so we can mess with it.

get_root_container() → pygame_gui.core.interfaces.container_interface.IUIContainerInterface

Returns the 'root' container. The one all UI elements are placed in by default if they are not placed anywhere else, fills the whole OS/pygame window.

Returns:A container.
get_shadow(size: Tuple[int, int], shadow_width: int = 2, shape: str = 'rectangle', corner_radius: int = 2) → pygame.surface.Surface

Returns a 'shadow' surface scaled to the requested size.

Parameters:
  • size -- The size of the object we are shadowing + it's shadow.
  • shadow_width -- The width of the shadowed edge.
  • shape -- The shape of the requested shadow.
  • corner_radius -- The radius of the shadow corners if this is a rectangular shadow.
Returns:

A shadow as a pygame Surface.

get_sprite_group() → pygame.sprite.LayeredDirty

Gets the sprite group used by the entire UI to keep it in the correct order for drawing and processing input.

Returns:The UI's sprite group.
get_theme() → pygame_gui.core.interfaces.appearance_theme_interface.IUIAppearanceThemeInterface

Gets the theme so the data in it can be accessed.

Returns:The theme data used by this UIManager
get_universal_empty_surface() → pygame.surface.Surface

Sometimes we want to hide sprites or just have sprites with no visual component, when we do we can just use this empty surface to save having lots of empty surfaces all over memory.

Returns:An empty, and therefore invisible pygame.surface.Surface
get_window_stack() → pygame_gui.core.interfaces.window_stack_interface.IUIWindowStackInterface

The UIWindowStack organises any windows in the UI Manager so that they are correctly sorted and move windows we interact with to the top of the stack.

Returns:The stack of windows.
preload_fonts(font_list: List[Dict[str, Union[str, int, float]]])

It's a good idea to pre-load the exact fonts your program uses during the loading phase of your program. By default the pygame_gui library will still work, but will spit out reminder warnings when you haven't done this. Loading fonts on the fly will slow down the apparent responsiveness when creating UI elements that use a lot of different fonts.

To pre-load custom fonts, or to use custom fonts at all (i.e. ones that aren't the default 'fira_code' font) you must first add the paths to the files for those fonts, then load the specific fonts with a list of font descriptions in a dictionary form like so:

{'name': 'fira_code', 'point_size': 12, 'style': 'bold_italic'}

You can specify size either in pygame.Font point sizes with 'point_size', or in HTML style sizes with 'html_size'. Style options are:

  • 'regular'
  • 'italic'
  • 'bold'
  • 'bold_italic'

The name parameter here must match the one you used when you added the file paths.

Parameters:font_list -- A list of font descriptions in dictionary format as described above.
print_layer_debug()

Print some formatted information on the current state of the UI Layers.

Handy for debugging layer problems.

print_unused_fonts()

Helps you identify which pre-loaded fonts you are actually still using in your project after you've fiddled around with the text a lot by printing out a list of fonts that have not been used yet at the time this function is called.

Of course if you don't run the code path in which a particular font is used before calling this function then it won't be of much use, so take it's results under advisement rather than as gospel.

process_events(event: pygame.event.Event)

This is the top level method through which all input to UI elements is processed and reacted to.

One of the key things it controls is the currently 'focused' element of which there can be only one at a time. It also manages 'consumed events' these events will not be passed on to elements below them in the GUI hierarchy and helps us stop buttons underneath windows from receiving input.

Parameters:event -- pygame.event.Event - the event to process.
Returns:A boolean indicating whether the event was consumed.
set_active_cursor(cursor: pygame.cursors.Cursor)

This is for users of the library to set the currently active cursor, it will be currently only be overridden by the resizing cursors.

The expected input is a pygame.cursors.Cursor:

manager.set_active_cursor(pygame.cursors.Cursor(pygame.SYSTEM_CURSOR_ARROW))
set_focus_set(focus: Union[pygame_gui.core.interfaces.element_interface.IUIElementInterface, Set[pygame_gui.core.interfaces.element_interface.IUIElementInterface]])

Set a set of element as the focused set.

Parameters:focus -- The set of element to focus on.
set_locale(locale: str)

Set a locale language code to use in the UIManager

Parameters:locale -- A two letter ISO 639-1 code for a supported language.

TODO: Make this raise an exception for an unsupported language?

set_text_input_hovered(hovering_text_input: bool)

Set to true when hovering an area text can be input into.

Currently switches the cursor to the I-Beam cursor.

Parameters:hovering_text_input -- set to True to toggle the I-Beam cursor
set_visual_debug_mode(is_active: bool)

Loops through all our UIElements to turn visual debug mode on or off. Also calls print_layer_debug()

Parameters:is_active -- True to activate visual debug and False to turn it off.
set_window_resolution(window_resolution: Tuple[int, int])

Sets the window resolution.

Parameters:window_resolution -- the resolution to set.
update(time_delta: float)

From here all our UI elements are updated and which element is currently 'hovered' is checked; which means the mouse pointer is overlapping them. This is managed centrally so we aren't ever overlapping two elements at once.

It also updates the shape cache to continue storing already created elements shapes in the long term cache, in case we need them later.

Finally, if live theme updates are enabled, it checks to see if the theme file has been modified and triggers all the UI elements to rebuild if it has.

Parameters:time_delta -- The time passed since the last call to update, in seconds.

Module contents

Pygame GUI module

Provides bits and bobs of UI to help make more complicated interactions with games built in pygame easier to accomplish.

class pygame_gui.UIManager(window_resolution: Tuple[int, int], theme_path: Union[str, pygame_gui.core.utility.PackageResource, None] = None, enable_live_theme_updates: bool = True, resource_loader: Optional[pygame_gui.core.resource_loaders.IResourceLoader] = None, starting_language: str = 'en', translation_directory_paths: Optional[List[str]] = None)

Bases: pygame_gui.core.interfaces.manager_interface.IUIManagerInterface

The UI Manager class helps keep track of all the moving parts in the pygame_gui system.

Before doing anything else with pygame_gui create a UIManager and remember to update it every frame.

Parameters:
  • window_resolution -- window resolution.
  • theme_path -- relative file path to theme.
  • enable_live_theme_updates -- Lets the theme update in-game after we edit the theme file
add_font_paths(font_name: str, regular_path: str, bold_path: str = None, italic_path: str = None, bold_italic_path: str = None)

Add file paths for custom fonts you want to use in the UI. For each font name you add you can specify font files for different styles. Fonts with designed styles tend to render a lot better than fonts that are forced to make use of pygame's bold and italic styling effects, so if you plan to use bold and italic text at small sizes - find fonts with these styles available as separate files.

The font name you specify here can be used to choose the font in the blocks of HTML-subset formatted text, available in some of the UI elements like the UITextBox.

It is recommended that you also pre-load any fonts you use at an appropriate moment in your project rather than letting the library dynamically load them when they are required. That is because dynamic loading of large font files can cause UI elements with a lot of font usage to appear rather slowly as they are waiting for the fonts they need to load.

Parameters:
  • font_name -- The name of the font that will be used to reference it elsewhere in the GUI.
  • regular_path -- The path of the font file for this font with no styles applied.
  • bold_path -- The path of the font file for this font with just bold style applied.
  • italic_path -- The path of the font file for this font with just italic style applied.
  • bold_italic_path -- The path of the font file for this font with bold & italic style applied.
calculate_scaled_mouse_position(position: Tuple[int, int]) → Tuple[int, int]

Scaling an input mouse position by a scale factor.

clear_and_reset()

Clear all existing windows and the root container, which should get rid of all created UI elements. We then recreate the UIWindowStack and the root container.

create_tool_tip(text: str, position: Tuple[int, int], hover_distance: Tuple[int, int], parent_element: pygame_gui.core.interfaces.element_interface.IUIElementInterface, object_id: pygame_gui.core.object_id.ObjectID, *, wrap_width: Optional[int] = None, text_kwargs: Optional[Dict[str, str]] = None) → pygame_gui.core.interfaces.tool_tip_interface.IUITooltipInterface

Creates a tool tip ands returns it. Have hidden this away in the manager so we can call it from other UI elements and create tool tips without creating cyclical import problems.

Parameters:
  • text -- The tool tips text, can utilise the HTML subset used in all UITextBoxes.
  • position -- The screen position to create the tool tip for.
  • hover_distance -- The distance we should hover away from our target position.
  • parent_element -- The UIElement that spawned this tool tip.
  • object_id -- the object_id of the tooltip.
  • wrap_width -- an optional width for the tool tip, will overwrite any value from the theme file.
  • text_kwargs -- a dictionary of variable arguments to pass to the translated string useful when you have multiple translations that need variables inserted in the middle.
Returns:

A tool tip placed somewhere on the screen.

draw_ui(window_surface: pygame.surface.Surface)

Draws all the UI elements on the screen. Generally you want this to be after the rest of your game sprites have been drawn.

If you want to do something particularly unusual with drawing you may have to write your own UI manager.

Parameters:window_surface -- The screen or window surface on which we are going to draw all of our UI Elements.
get_double_click_time() → float

Returns time between clicks that counts as a double click.

Returns:A float, time measured in seconds.
get_focus_set()

Gets the focused set.

Returns:The set of elements that currently have interactive focus. If None, nothing is currently focused.
get_hovering_any_element() → bool

True if any UI element (other than the root container) is hovered by the mouse.

Combined with 'get_focus_set()' and the return value from process_events(), it should make it easier to switch input events between the UI and other parts of an application.

get_locale()

Get the locale language code being used in the UIManager

Returns:A two letter ISO 639-1 code for the current locale.
get_mouse_position() → Tuple[int, int]

Wrapping pygame mouse position so we can mess with it.

get_root_container() → pygame_gui.core.interfaces.container_interface.IUIContainerInterface

Returns the 'root' container. The one all UI elements are placed in by default if they are not placed anywhere else, fills the whole OS/pygame window.

Returns:A container.
get_shadow(size: Tuple[int, int], shadow_width: int = 2, shape: str = 'rectangle', corner_radius: int = 2) → pygame.surface.Surface

Returns a 'shadow' surface scaled to the requested size.

Parameters:
  • size -- The size of the object we are shadowing + it's shadow.
  • shadow_width -- The width of the shadowed edge.
  • shape -- The shape of the requested shadow.
  • corner_radius -- The radius of the shadow corners if this is a rectangular shadow.
Returns:

A shadow as a pygame Surface.

get_sprite_group() → pygame.sprite.LayeredDirty

Gets the sprite group used by the entire UI to keep it in the correct order for drawing and processing input.

Returns:The UI's sprite group.
get_theme() → pygame_gui.core.interfaces.appearance_theme_interface.IUIAppearanceThemeInterface

Gets the theme so the data in it can be accessed.

Returns:The theme data used by this UIManager
get_universal_empty_surface() → pygame.surface.Surface

Sometimes we want to hide sprites or just have sprites with no visual component, when we do we can just use this empty surface to save having lots of empty surfaces all over memory.

Returns:An empty, and therefore invisible pygame.surface.Surface
get_window_stack() → pygame_gui.core.interfaces.window_stack_interface.IUIWindowStackInterface

The UIWindowStack organises any windows in the UI Manager so that they are correctly sorted and move windows we interact with to the top of the stack.

Returns:The stack of windows.
preload_fonts(font_list: List[Dict[str, Union[str, int, float]]])

It's a good idea to pre-load the exact fonts your program uses during the loading phase of your program. By default the pygame_gui library will still work, but will spit out reminder warnings when you haven't done this. Loading fonts on the fly will slow down the apparent responsiveness when creating UI elements that use a lot of different fonts.

To pre-load custom fonts, or to use custom fonts at all (i.e. ones that aren't the default 'fira_code' font) you must first add the paths to the files for those fonts, then load the specific fonts with a list of font descriptions in a dictionary form like so:

{'name': 'fira_code', 'point_size': 12, 'style': 'bold_italic'}

You can specify size either in pygame.Font point sizes with 'point_size', or in HTML style sizes with 'html_size'. Style options are:

  • 'regular'
  • 'italic'
  • 'bold'
  • 'bold_italic'

The name parameter here must match the one you used when you added the file paths.

Parameters:font_list -- A list of font descriptions in dictionary format as described above.
print_layer_debug()

Print some formatted information on the current state of the UI Layers.

Handy for debugging layer problems.

print_unused_fonts()

Helps you identify which pre-loaded fonts you are actually still using in your project after you've fiddled around with the text a lot by printing out a list of fonts that have not been used yet at the time this function is called.

Of course if you don't run the code path in which a particular font is used before calling this function then it won't be of much use, so take it's results under advisement rather than as gospel.

process_events(event: pygame.event.Event)

This is the top level method through which all input to UI elements is processed and reacted to.

One of the key things it controls is the currently 'focused' element of which there can be only one at a time. It also manages 'consumed events' these events will not be passed on to elements below them in the GUI hierarchy and helps us stop buttons underneath windows from receiving input.

Parameters:event -- pygame.event.Event - the event to process.
Returns:A boolean indicating whether the event was consumed.
set_active_cursor(cursor: pygame.cursors.Cursor)

This is for users of the library to set the currently active cursor, it will be currently only be overridden by the resizing cursors.

The expected input is a pygame.cursors.Cursor:

manager.set_active_cursor(pygame.cursors.Cursor(pygame.SYSTEM_CURSOR_ARROW))
set_focus_set(focus: Union[pygame_gui.core.interfaces.element_interface.IUIElementInterface, Set[pygame_gui.core.interfaces.element_interface.IUIElementInterface]])

Set a set of element as the focused set.

Parameters:focus -- The set of element to focus on.
set_locale(locale: str)

Set a locale language code to use in the UIManager

Parameters:locale -- A two letter ISO 639-1 code for a supported language.

TODO: Make this raise an exception for an unsupported language?

set_text_input_hovered(hovering_text_input: bool)

Set to true when hovering an area text can be input into.

Currently switches the cursor to the I-Beam cursor.

Parameters:hovering_text_input -- set to True to toggle the I-Beam cursor
set_visual_debug_mode(is_active: bool)

Loops through all our UIElements to turn visual debug mode on or off. Also calls print_layer_debug()

Parameters:is_active -- True to activate visual debug and False to turn it off.
set_window_resolution(window_resolution: Tuple[int, int])

Sets the window resolution.

Parameters:window_resolution -- the resolution to set.
update(time_delta: float)

From here all our UI elements are updated and which element is currently 'hovered' is checked; which means the mouse pointer is overlapping them. This is managed centrally so we aren't ever overlapping two elements at once.

It also updates the shape cache to continue storing already created elements shapes in the long term cache, in case we need them later.

Finally, if live theme updates are enabled, it checks to see if the theme file has been modified and triggers all the UI elements to rebuild if it has.

Parameters:time_delta -- The time passed since the last call to update, in seconds.
class pygame_gui.PackageResource(package: str, resource: str)

Bases: object

A data class to handle input for importlib.resources as single parameter.

Parameters:
  • package -- The python package our resource is located in (e.g. 'pygame_gui.data')
  • resource -- The name of the resource (e.g. 'default_theme.json')
to_path() → str

If we don't have any importlib module to use, we can try to turn the resource into a file path.

Returns:A string path.
class pygame_gui.UITextEffectType(name)

Bases: object

A Type for Text effect constants, so we can mess with them later if needs be