pygame_gui package

Subpackages

Submodules

pygame_gui.ui_manager module

class pygame_gui.ui_manager.UIManager(window_resolution: Tuple[int, int], theme_path: str | PathLike | StringIO | PackageResource | dict | None = None, enable_live_theme_updates: bool = True, resource_loader: IResourceLoader | None = None, starting_language: str = 'en', translation_directory_paths: List[str] | None = None)

Bases: IUIManagerInterface

The UIManager is the central coordinator for all UI elements in pygame_gui. It manages the lifecycle, rendering, and event handling of UI components while maintaining proper layering and focus management.

Key Responsibilities: - Manages UI element creation, updates, and rendering - Handles event processing and focus management - Maintains UI element layering and window stacking - Manages themes and visual styling - Coordinates mouse interactions and cursor changes

Role in pygame_gui Ecosystem: The UIManager acts as the bridge between pygame's core functionality and pygame_gui's UI elements. It ensures proper coordination between different UI components and maintains the visual hierarchy.

UI Element Layering: ` +------------------+ |    Window 3      |  Layer 3 (Top) +------------------+ |    Window 2      |  Layer 2 +------------------+ |    Window 1      |  Layer 1 +------------------+ |  Root Container  |  Layer 0 (Bottom) +------------------+ `

Event Processing Flow: ``` pygame Event

│ ▼

UIManager.process_events()

│ ▼

Top Layer Elements

│ ▼

Middle Layer Elements

│ ▼

Bottom Layer Elements

│ ▼

Event Consumed? ──Yes──► Stop Processing

│ No ▼

Continue to Game Logic ```

Quick Start Example: ```python import pygame import pygame_gui

pygame.init() screen = pygame.display.set_mode((800, 600)) ui_manager = pygame_gui.UIManager((800, 600))

# Create UI elements button = pygame_gui.elements.UIButton(

relative_rect=pygame.Rect((350, 275), (100, 50)), text='Hello', manager=ui_manager

)

# Main game loop while True:

time_delta = clock.tick(60)/1000.0

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

pygame.quit() exit()

ui_manager.process_events(event)

ui_manager.update(time_delta) screen.fill((0, 0, 0)) ui_manager.draw_ui(screen) pygame.display.update()

```

Common Use Cases: 1. Creating and managing UI windows and dialogs 2. Handling user input and events 3. Managing UI element focus and layering 4. Applying and updating themes 5. Coordinating mouse interactions

Best Practices: 1. Create only one UIManager instance per application 2. Call update() and draw_ui() every frame 3. Process events through the manager before handling game events 4. Use containers to group related UI elements 5. Preload fonts to avoid runtime loading delays

Performance Considerations: 1. Limit the number of UI elements to prevent performance degradation 2. Use containers to group elements and improve event processing 3. Preload fonts during initialization 4. Disable live theme updates in production 5. Use appropriate layer management for complex UIs

Parameters:
  • window_resolution -- The resolution of the window/screen the UI will be displayed on.

  • theme_path -- Optional path to a theme file or theme dictionary. If None, uses default theme.

  • enable_live_theme_updates -- Whether to enable live theme file updates during runtime.

  • resource_loader -- Optional custom resource loader. If None, uses default BlockingThreadedResourceLoader.

  • starting_language -- The initial language code for UI text (default: "en").

  • translation_directory_paths -- Optional list of paths to translation files.

add_font_paths(font_name: str, regular_path: str, bold_path: str | None = None, italic_path: str | None = None, bold_italic_path: str | None = 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 preload 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.

property copy_text_enabled: bool

Get whether we can copy any text.

Returns:

True if we can Copy text

create_new_theme(theme_path: str | PathLike | StringIO | PackageResource | dict | None = None) UIAppearanceTheme

Create a new theme using self information. :param theme_path: relative file path to theme or theme dictionary.

create_tool_tip(text: str, position: Tuple[int, int], hover_distance: Tuple[int, int], parent_element: IUIElementInterface, object_id: ObjectID | None, *, wrap_width: int | None = None, text_kwargs: Dict[str, str] | None = None) IUITooltipInterface

Create a tooltip that appears when hovering over a UI element.

The tooltip is positioned relative to the parent element and will automatically adjust its position to stay within the screen bounds. The tooltip can use HTML formatting for text styling.

Example: ```python # Create a tooltip for a button tooltip = ui_manager.create_tool_tip(

text="Click me!", position=(100, 100), hover_distance=(10, 10), parent_element=my_button, object_id=ObjectID("#tooltip", "button_tooltip")

)

param text:

The tooltip text, can utilise the HTML subset used in all UITextBoxes.

param position:

The screen position to create the tooltip for.

param hover_distance:

The distance we should hover away from our target position.

param parent_element:

The UIElement that spawned this tooltip.

param object_id:

The object_id of the tooltip for theming.

param wrap_width:

Optional width for the tooltip, overrides theme value.

param text_kwargs:

Dictionary of variables for text translation.

return:

A tooltip placed somewhere on the screen.

raises:

ValueError if position or hover_distance are invalid

draw_ui(window_surface: Surface)

Draw all UI elements onto the provided surface. This method should be called after drawing the game's background but before updating the display.

The drawing process: 1. Elements are drawn in order from bottom-most to top-most 2. Each element is drawn according to its current state and theme 3. Elements outside the visible area are automatically clipped

Important Notes: - The surface should normally be the same size as the window resolution - For transparent surfaces, use premultiplied alpha blending - Drawing order matters for proper layering

Example: ```python # In your game loop while True:

# Draw game background screen.fill((0, 0, 0))

# Draw game elements draw_game_elements(screen)

# Draw UI on top ui_manager.draw_ui(screen)

# Update display pygame.display.update()

```

Parameters:

window_surface -- The surface to draw UI elements on. Should normally be the same size as the window resolution. If using transparency, the surface should use premultiplied alpha blending.

See Also: - https://pyga.me/docs/tutorials/en/premultiplied-alpha.html for information about

premultiplied alpha blending

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() IContainerAndContainerLike | None

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: List[int] | None = None) 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() LayeredGUIGroup

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() IUIAppearanceThemeInterface

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

Returns:

The theme data used by this UIManager

get_universal_empty_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() 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.

property paste_text_enabled: bool

Get whether we can paste any text.

Returns:

True if we can Paste text

preload_fonts(font_list: List[Dict[str, str | int | float]])

It's a good idea to preload 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 preload custom fonts, or to use custom fonts at all (i.e. ones that aren't the default 'noto_sans' 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': 'noto_sans', 'point_size': 12, 'style': 'bold_italic', 'antialiased': 1}

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 preloaded 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 its results under advisement rather than as gospel.

process_events(event: Event)

Process pygame events and distribute them to appropriate UI elements. This is the main entry point for handling user input in the UI system.

The method processes events in order from top-most to bottom-most UI elements, ensuring that elements higher in the visual stack receive events first. Events are considered "consumed" when a UI element handles them, preventing them from being passed to elements below.

Side Effects: - May change the focused element - May trigger UI element state changes - May generate UI events (e.g., button clicks)

Example: ```python # In your game loop for event in pygame.event.get():

if event.type == pygame.QUIT:

pygame.quit() exit()

# Process UI events first ui_manager.process_events(event)

# Then handle game events if not ui_manager.get_hovering_any_element():

handle_game_events(event)

```

Parameters:

event -- The pygame event to process. Must be a valid pygame.event.Event object.

Returns:

True if the event was consumed by a UI element, False otherwise.

rebuild_all_from_changed_theme_data(theme: IUIAppearanceThemeInterface | None = None)

Rebuild the entire UI after a change in the theming.

Parameters:

theme -- the theme that has changed.

set_active_cursor(cursor: 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: IUIElementInterface | Set[IUIElementInterface] | None)

Set the focus to a single UI element or a set of related UI elements.

When an element or set of elements receives focus: 1. Previously focused elements are unfocused 2. The new element(s) receive focus 3. Focus-related events are triggered 4. Visual focus indicators are updated

Type Parameters: - focus: Optional[Union[IUIElementInterface, Set[IUIElementInterface]]]

  • None: Remove focus from all elements

  • IUIElementInterface: Focus a single element

  • Set[IUIElementInterface]: Focus multiple related elements

Example: ```python # Focus a single element ui_manager.set_focus_set(my_button)

# Focus a set of related elements ui_manager.set_focus_set({text_input, submit_button})

# Remove focus ui_manager.set_focus_set(None) ```

Parameters:

focus -- The element or set of elements to focus on.

Raises:

TypeError if focus parameter is of invalid type

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_hovered(hovering_text_input: bool)

Set to true when hovering an area containing selectable text.

Currently, switches the cursor to the I-Beam cursor.

Parameters:

hovering_text_input -- set to True to toggle the I-Beam cursor

set_ui_theme(theme: IUIAppearanceThemeInterface, update_all_sprites: bool = False)

Set ui theme.

Parameters:
  • theme -- The theme to set.

  • update_all_sprites

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)

Update the state of all UI elements and handle hover effects. This method should be called every frame to ensure proper UI element behavior.

The update process includes: 1. Checking for theme file changes (if live updates enabled) 2. Updating mouse position and hover states 3. Updating all UI elements 4. Managing cursor changes based on hover state

Side Effects: - Updates element hover states - May change the cursor appearance - May trigger theme reloads - Updates element animations and timers

Example: ```python # In your game loop clock = pygame.time.Clock() while True:

time_delta = clock.tick(60)/1000.0 # Time in seconds since last frame

# Update UI ui_manager.update(time_delta)

# Update game state update_game_state(time_delta)

```

Parameters:

time_delta -- Time in seconds since the last update call. Used for animations and timing.

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.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.UIManager(window_resolution: Tuple[int, int], theme_path: str | PathLike | StringIO | PackageResource | dict | None = None, enable_live_theme_updates: bool = True, resource_loader: IResourceLoader | None = None, starting_language: str = 'en', translation_directory_paths: List[str] | None = None)

Bases: IUIManagerInterface

The UIManager is the central coordinator for all UI elements in pygame_gui. It manages the lifecycle, rendering, and event handling of UI components while maintaining proper layering and focus management.

Key Responsibilities: - Manages UI element creation, updates, and rendering - Handles event processing and focus management - Maintains UI element layering and window stacking - Manages themes and visual styling - Coordinates mouse interactions and cursor changes

Role in pygame_gui Ecosystem: The UIManager acts as the bridge between pygame's core functionality and pygame_gui's UI elements. It ensures proper coordination between different UI components and maintains the visual hierarchy.

UI Element Layering: ` +------------------+ |    Window 3      |  Layer 3 (Top) +------------------+ |    Window 2      |  Layer 2 +------------------+ |    Window 1      |  Layer 1 +------------------+ |  Root Container  |  Layer 0 (Bottom) +------------------+ `

Event Processing Flow: ``` pygame Event

│ ▼

UIManager.process_events()

│ ▼

Top Layer Elements

│ ▼

Middle Layer Elements

│ ▼

Bottom Layer Elements

│ ▼

Event Consumed? ──Yes──► Stop Processing

│ No ▼

Continue to Game Logic ```

Quick Start Example: ```python import pygame import pygame_gui

pygame.init() screen = pygame.display.set_mode((800, 600)) ui_manager = pygame_gui.UIManager((800, 600))

# Create UI elements button = pygame_gui.elements.UIButton(

relative_rect=pygame.Rect((350, 275), (100, 50)), text='Hello', manager=ui_manager

)

# Main game loop while True:

time_delta = clock.tick(60)/1000.0

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

pygame.quit() exit()

ui_manager.process_events(event)

ui_manager.update(time_delta) screen.fill((0, 0, 0)) ui_manager.draw_ui(screen) pygame.display.update()

```

Common Use Cases: 1. Creating and managing UI windows and dialogs 2. Handling user input and events 3. Managing UI element focus and layering 4. Applying and updating themes 5. Coordinating mouse interactions

Best Practices: 1. Create only one UIManager instance per application 2. Call update() and draw_ui() every frame 3. Process events through the manager before handling game events 4. Use containers to group related UI elements 5. Preload fonts to avoid runtime loading delays

Performance Considerations: 1. Limit the number of UI elements to prevent performance degradation 2. Use containers to group elements and improve event processing 3. Preload fonts during initialization 4. Disable live theme updates in production 5. Use appropriate layer management for complex UIs

Parameters:
  • window_resolution -- The resolution of the window/screen the UI will be displayed on.

  • theme_path -- Optional path to a theme file or theme dictionary. If None, uses default theme.

  • enable_live_theme_updates -- Whether to enable live theme file updates during runtime.

  • resource_loader -- Optional custom resource loader. If None, uses default BlockingThreadedResourceLoader.

  • starting_language -- The initial language code for UI text (default: "en").

  • translation_directory_paths -- Optional list of paths to translation files.

add_font_paths(font_name: str, regular_path: str, bold_path: str | None = None, italic_path: str | None = None, bold_italic_path: str | None = 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 preload 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.

property copy_text_enabled: bool

Get whether we can copy any text.

Returns:

True if we can Copy text

create_new_theme(theme_path: str | PathLike | StringIO | PackageResource | dict | None = None) UIAppearanceTheme

Create a new theme using self information. :param theme_path: relative file path to theme or theme dictionary.

create_tool_tip(text: str, position: Tuple[int, int], hover_distance: Tuple[int, int], parent_element: IUIElementInterface, object_id: ObjectID | None, *, wrap_width: int | None = None, text_kwargs: Dict[str, str] | None = None) IUITooltipInterface

Create a tooltip that appears when hovering over a UI element.

The tooltip is positioned relative to the parent element and will automatically adjust its position to stay within the screen bounds. The tooltip can use HTML formatting for text styling.

Example: ```python # Create a tooltip for a button tooltip = ui_manager.create_tool_tip(

text="Click me!", position=(100, 100), hover_distance=(10, 10), parent_element=my_button, object_id=ObjectID("#tooltip", "button_tooltip")

)

param text:

The tooltip text, can utilise the HTML subset used in all UITextBoxes.

param position:

The screen position to create the tooltip for.

param hover_distance:

The distance we should hover away from our target position.

param parent_element:

The UIElement that spawned this tooltip.

param object_id:

The object_id of the tooltip for theming.

param wrap_width:

Optional width for the tooltip, overrides theme value.

param text_kwargs:

Dictionary of variables for text translation.

return:

A tooltip placed somewhere on the screen.

raises:

ValueError if position or hover_distance are invalid

draw_ui(window_surface: Surface)

Draw all UI elements onto the provided surface. This method should be called after drawing the game's background but before updating the display.

The drawing process: 1. Elements are drawn in order from bottom-most to top-most 2. Each element is drawn according to its current state and theme 3. Elements outside the visible area are automatically clipped

Important Notes: - The surface should normally be the same size as the window resolution - For transparent surfaces, use premultiplied alpha blending - Drawing order matters for proper layering

Example: ```python # In your game loop while True:

# Draw game background screen.fill((0, 0, 0))

# Draw game elements draw_game_elements(screen)

# Draw UI on top ui_manager.draw_ui(screen)

# Update display pygame.display.update()

```

Parameters:

window_surface -- The surface to draw UI elements on. Should normally be the same size as the window resolution. If using transparency, the surface should use premultiplied alpha blending.

See Also: - https://pyga.me/docs/tutorials/en/premultiplied-alpha.html for information about

premultiplied alpha blending

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() IContainerAndContainerLike | None

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: List[int] | None = None) 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() LayeredGUIGroup

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() IUIAppearanceThemeInterface

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

Returns:

The theme data used by this UIManager

get_universal_empty_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() 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.

property paste_text_enabled: bool

Get whether we can paste any text.

Returns:

True if we can Paste text

preload_fonts(font_list: List[Dict[str, str | int | float]])

It's a good idea to preload 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 preload custom fonts, or to use custom fonts at all (i.e. ones that aren't the default 'noto_sans' 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': 'noto_sans', 'point_size': 12, 'style': 'bold_italic', 'antialiased': 1}

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 preloaded 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 its results under advisement rather than as gospel.

process_events(event: Event)

Process pygame events and distribute them to appropriate UI elements. This is the main entry point for handling user input in the UI system.

The method processes events in order from top-most to bottom-most UI elements, ensuring that elements higher in the visual stack receive events first. Events are considered "consumed" when a UI element handles them, preventing them from being passed to elements below.

Side Effects: - May change the focused element - May trigger UI element state changes - May generate UI events (e.g., button clicks)

Example: ```python # In your game loop for event in pygame.event.get():

if event.type == pygame.QUIT:

pygame.quit() exit()

# Process UI events first ui_manager.process_events(event)

# Then handle game events if not ui_manager.get_hovering_any_element():

handle_game_events(event)

```

Parameters:

event -- The pygame event to process. Must be a valid pygame.event.Event object.

Returns:

True if the event was consumed by a UI element, False otherwise.

rebuild_all_from_changed_theme_data(theme: IUIAppearanceThemeInterface | None = None)

Rebuild the entire UI after a change in the theming.

Parameters:

theme -- the theme that has changed.

set_active_cursor(cursor: 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: IUIElementInterface | Set[IUIElementInterface] | None)

Set the focus to a single UI element or a set of related UI elements.

When an element or set of elements receives focus: 1. Previously focused elements are unfocused 2. The new element(s) receive focus 3. Focus-related events are triggered 4. Visual focus indicators are updated

Type Parameters: - focus: Optional[Union[IUIElementInterface, Set[IUIElementInterface]]]

  • None: Remove focus from all elements

  • IUIElementInterface: Focus a single element

  • Set[IUIElementInterface]: Focus multiple related elements

Example: ```python # Focus a single element ui_manager.set_focus_set(my_button)

# Focus a set of related elements ui_manager.set_focus_set({text_input, submit_button})

# Remove focus ui_manager.set_focus_set(None) ```

Parameters:

focus -- The element or set of elements to focus on.

Raises:

TypeError if focus parameter is of invalid type

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_hovered(hovering_text_input: bool)

Set to true when hovering an area containing selectable text.

Currently, switches the cursor to the I-Beam cursor.

Parameters:

hovering_text_input -- set to True to toggle the I-Beam cursor

set_ui_theme(theme: IUIAppearanceThemeInterface, update_all_sprites: bool = False)

Set ui theme.

Parameters:
  • theme -- The theme to set.

  • update_all_sprites

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)

Update the state of all UI elements and handle hover effects. This method should be called every frame to ensure proper UI element behavior.

The update process includes: 1. Checking for theme file changes (if live updates enabled) 2. Updating mouse position and hover states 3. Updating all UI elements 4. Managing cursor changes based on hover state

Side Effects: - Updates element hover states - May change the cursor appearance - May trigger theme reloads - Updates element animations and timers

Example: ```python # In your game loop clock = pygame.time.Clock() while True:

time_delta = clock.tick(60)/1000.0 # Time in seconds since last frame

# Update UI ui_manager.update(time_delta)

# Update game state update_game_state(time_delta)

```

Parameters:

time_delta -- Time in seconds since the last update call. Used for animations and timing.

class pygame_gui.UITextEffectType(name)

Bases: object

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

pygame_gui.performance_monitor(operation_name: str)

Decorator to monitor performance of operations and identify bottlenecks.

This decorator measures the execution time of functions and logs a warning if the operation takes longer than 16.67 milliseconds (60 FPS frame time). This helps identify performance issues that could impact UI responsiveness in real-time applications.

Parameters:

operation_name -- A descriptive name for the operation being monitored.

Example usage:

@performance_monitor("Theme Loading") def load_theme_data(self):

# ... complex theme loading logic ... pass

The decorator will automatically log slow operations like:

"SLOW OPERATION: Theme Loading took 25.43ms"