pygame_gui.core package

Submodules

pygame_gui.core.colour_gradient module

class pygame_gui.core.colour_gradient.ColourGradient(angle_direction: int, colour_1: pygame.Color, colour_2: pygame.Color, colour_3: Optional[pygame.Color] = None)

Bases: pygame_gui.core.interfaces.colour_gradient_interface.IColourGradientInterface

Creates a small surface containing a smooth gradient between two or three colours.

Parameters:
  • angle_direction -- Angle direction of the gradient in degrees.
  • colour_1 -- The first colour of the gradient.
  • colour_2 -- The second colour of the gradient.
  • colour_3 -- An optional third colour for the gradient.
apply_gradient_to_surface(input_surface: pygame.Surface, rect: Optional[pygame.Rect] = None)

Applies this gradient to a specified input surface using blending multiplication. As a result this method works best when the input surface is a mostly white, stencil shape type surface.

Parameters:
  • input_surface --
  • rect -- The rectangle on the surface to apply the gradient to. If None, applies to the whole surface.

pygame_gui.core.surface_cache module

class pygame_gui.core.surface_cache.SurfaceCache

Bases: object

A cache for surfaces that we estimate the UI may want to reuse to save constantly remaking almost identical drawable shapes.

add_surface_to_cache(surface: pygame.Surface, string_id: str)

Adds a surface to the cache. There are two levels to the cache, the short term level just keeps hold of the surface until we have time to add it to the long term level.

Parameters:
  • surface -- The surface to add to the cache.
  • string_id -- An ID to store the surface under to make it easy to recall later.
add_surface_to_long_term_cache(cached_item: List[Union[pygame.Surface, int]], string_id: str)

Move a surface from the short term cache into the long term one.

Parameters:
  • cached_item -- The surface to move into the long term cache.
  • string_id -- The ID of the surface in the cache.
static build_cache_id(shape: str, size: Tuple[int, int], shadow_width: int, border_width: int, border_colour: pygame.Color, bg_colour: pygame.Color, corner_radius: Optional[int] = None) → str

Create an ID string for a surface based on it's dimensions and parameters. The idea is that any surface in the cache with the same values in this ID should be identical.

Parameters:
  • shape -- A string for the overall shape of the surface (rounded rectangle, rectangle, etc).
  • size -- The dimensions of the surface.
  • shadow_width -- The thickness of the shadow around the shape.
  • border_width -- The thickness of the border around the shape.
  • border_colour -- The colour of the border.
  • bg_colour -- The background, or main colour of the surface.
  • corner_radius -- Optional corner radius parameter, only used for rounded rectangles.
Returns:

A assembled string ID from the provided data.

find_surface_in_cache(lookup_id: str) → Optional[pygame.Surface]

Looks for a surface in the cache by an ID and returns it if found.

Parameters:lookup_id -- ID of the surface to look for in the cache.

:return The found surface, or None.

remove_user_and_request_clean_up_of_cached_item(string_id: str)

If we are certain that a cached surface won't be used again anytime soon we can request it is removed from the cache directly.

Parameters:string_id -- the ID of the cached surface to remove from the cache.
remove_user_from_cache_item(string_id: str)

Deduct a 'user' from a particular cache surface. The number of users of a cache surface over the lifetime of a program would be a decent measure of how 'valuable' it is to keep a surface in the cache.

Parameters:string_id -- The ID of the cached surface to deduct a user from.
static split_rect(found_rectangle_to_split: pygame.Rect, dividing_rect: pygame.Rect, free_space_rectangles: List[pygame.Rect])

Takes an existing free space rectangle that we are placing a new surface inside of and then divides up the remaining space into new, smaller free space rectangles.

Parameters:
  • found_rectangle_to_split -- The rectangle we are spliting.
  • dividing_rect -- The rectangle dividing up the split rectangle.
  • free_space_rectangles -- A list of all free space rectangles for a particular surface.
update()

Takes care of steadily moving surfaces from the short term cache into the long term. Long term caching takes a while so we limit it to adding one surface a frame.

We also purge some lesser used surfaces from the long term cache when we run out of space.

pygame_gui.core.ui_appearance_theme module

class pygame_gui.core.ui_appearance_theme.UIAppearanceTheme(resource_loader: pygame_gui.core.resource_loaders.IResourceLoader, locale: str)

Bases: pygame_gui.core.interfaces.appearance_theme_interface.IUIAppearanceThemeInterface

The Appearance Theme class handles all the data that styles and generally dictates the appearance of UI elements across the whole UI.

The styling is split into four general areas:

  • colours - spelled in the British English fashion with a 'u'.
  • font - specifying a font to use for a UIElement where that is a relevant consideration.
  • images - describing any images to be used in a UIElement.
  • misc - covering all other types of data and stored as strings.

To change the theming for the UI you normally specify a theme file when creating the UIManager. For more information on theme files see the specific documentation elsewhere.

build_all_combined_ids(element_ids: Union[None, List[str]], class_ids: Union[None, List[Optional[str]]], object_ids: Union[None, List[Optional[str]]]) → List[str]

Construct a list of combined element ids from the element's various accumulated ids.

Parameters:
  • element_ids -- All the ids of elements this element is contained within.
  • class_ids -- All the ids of 'classes' that this element is contained within.
  • object_ids -- All the ids of objects this element is contained within.
Returns:

A list of IDs that reference this element in order of decreasing specificity.

check_need_to_reload() → bool

Check if we need to reload our theme file because it's been modified. If so, trigger a reload and return True so that the UIManager can trigger elements to rebuild from the theme data.

Return bool:True if we need to reload elements because the theme data has changed.
get_colour(colour_id: str, combined_element_ids: List[str] = None) → pygame.Color

Uses data about a UI element and a specific ID to find a colour from our theme.

Parameters:
  • combined_element_ids -- A list of IDs representing an element's location in a hierarchy of elements.
  • colour_id -- The id for the specific colour we are looking for.
Return pygame.Color:
 

A pygame colour.

get_colour_or_gradient(colour_id: str, combined_ids: List[str] = None) → Union[pygame.Color, pygame_gui.core.interfaces.colour_gradient_interface.IColourGradientInterface]

Uses data about a UI element and a specific ID to find a colour, or a gradient, from our theme. Use this function if the UIElement can handle either type.

Parameters:
  • combined_ids -- A list of IDs representing an element's location in a hierarchy of elements.
  • colour_id -- The id for the specific colour we are looking for.
Return pygame.Color or ColourGradient:
 

A colour or a gradient object.

get_font(combined_element_ids: List[str]) → _freetype.Font

Uses some data about a UIElement to get a font object.

Parameters:combined_element_ids -- A list of IDs representing an element's location in a interleaved hierarchy of elements.
Return pygame.freetype.Font:
 A pygame font object.
get_font_dictionary() → pygame_gui.core.interfaces.font_dictionary_interface.IUIFontDictionaryInterface

Lets us grab the font dictionary, which is created by the theme object, so we can access it directly.

Returns:The font dictionary.
get_font_info(combined_element_ids: List[str]) → Dict[str, Any]

Uses some data about a UIElement to get font data as dictionary

Parameters:combined_element_ids -- A list of IDs representing an element's location in a interleaved hierarchy of elements.
Return dictionary:
 Data about the font requested
get_image(image_id: str, combined_element_ids: List[str]) → pygame.Surface

Will raise an exception if no image with the ids specified is found. UI elements that have an optional image display will need to handle the exception.

Parameters:
  • combined_element_ids -- A list of IDs representing an element's location in a hierarchy of elements.
  • image_id -- The id identifying the particular image spot in the UI we are looking for an image to add to.
Returns:

A pygame.surface.Surface

get_misc_data(misc_data_id: str, combined_element_ids: List[str]) → Union[str, Dict[KT, VT]]

Uses data about a UI element and a specific ID to try and find a piece of miscellaneous theming data. Raises an exception if it can't find the data requested, UI elements requesting optional data will need to handle this exception.

Parameters:
  • combined_element_ids -- A list of IDs representing an element's location in a hierarchy of elements.
  • misc_data_id -- The id for the specific piece of miscellaneous data we are looking for.
Return Any:

Returns a string or a Dict

load_theme(file_path: Union[str, os.PathLike, _io.StringIO, pygame_gui.core.utility.PackageResource])

Loads a theme file, and currently, all associated data like fonts and images required by the theme.

Parameters:file_path -- The path to the theme we want to load.
reload_theming()

We need to load our theme file to see if anything expensive has changed, if so trigger it to reload/rebuild.

set_locale(locale: str)

Set the locale used in the appearance theme.

Parameters:locale -- a two letter ISO country code.
update_caching(time_delta: float)

Updates the various surface caches.

update_single_element_theming(element_name: str, new_theming_data: str)

Update theming data, via string - for a single element. :param element_name: :param new_theming_data: :return:

update_theming(new_theming_data: str, rebuild_all: bool = True)

Update theming data, via string - for the whole UI.

Parameters:
  • new_theming_data --
  • rebuild_all --
Returns:

pygame_gui.core.ui_element module

class pygame_gui.core.ui_element.ObjectID(object_id, class_id)

Bases: tuple

class_id

Alias for field number 1

object_id

Alias for field number 0

class pygame_gui.core.ui_element.UIElement(relative_rect: Union[pygame.Rect, Tuple[int, int, int, int]], manager: Optional[pygame_gui.core.interfaces.manager_interface.IUIManagerInterface], container: Optional[pygame_gui.core.interfaces.container_interface.IContainerLikeInterface], *, starting_height: int, layer_thickness: int, anchors: Dict[str, Union[str, UIElement]] = None, visible: int = 1)

Bases: pygame_gui.core.layered_gui_group.GUISprite, pygame_gui.core.interfaces.element_interface.IUIElementInterface

A base class for UI elements. You shouldn't create UI Element objects, instead all UI Element classes should derive from this class. Inherits from pygame.sprite.Sprite.

Parameters:
  • relative_rect -- A rectangle shape of the UI element, the position is relative to the element's container.
  • manager -- The UIManager that manages this UIElement.
  • container -- A container that this element is contained in.
  • starting_height -- Used to record how many layers above it's container this element should be. Normally 1.
  • layer_thickness -- Used to record how 'thick' this element is in layers. Normally 1.
  • anchors -- A dictionary describing what this element's relative_rect is relative to.
  • visible -- Whether the element is visible by default. Warning - container visibility may override this.
can_hover() → bool

A stub method to override. Called to test if this method can be hovered.

change_layer(new_layer: int)

Changes the layer this element is on.

Parameters:new_layer -- The layer to change this element to.
check_hover(time_delta: float, hovered_higher_element: bool) → bool

A method that helps us to determine which, if any, UI Element is currently being hovered by the mouse.

Parameters:
  • time_delta -- A float, the time in seconds between the last call to this function and now (roughly).
  • hovered_higher_element -- A boolean, representing whether we have already hovered a 'higher' element.
Return bool:

A boolean that is true if we have hovered a UI element, either just now or before this method.

disable()

Disables elements so they are no longer interactive. This is just a default fallback implementation for elements that don't define their own.

Elements should handle their own enabling and disabling.

enable()

Enables elements so they are interactive again. This is just a default fallback implementation for elements that don't define their own.

Elements should handle their own enabling and disabling.

focus()

A stub to override. Called when we focus this UI element.

get_abs_rect() → pygame.Rect

The absolute positioning rect.

Returns:A pygame rect.
get_anchor_targets() → list

Get any anchor targets this element has so we can update them when their targets change :return: the list of anchor targets.

get_element_ids() → List[str]

A list of all the element IDs in this element's theming/event hierarchy.

Returns:a list of strings, one ofr each element in the hierarchy.
get_focus_set() → Set[pygame_gui.core.ui_element.UIElement]

Return the set of elements to focus when we focus this element.

get_image_clipping_rect() → Optional[pygame.Rect]

Obtain the current image clipping rect.

Returns:The current clipping rect. May be None.
get_relative_rect() → pygame.Rect

The relative positioning rect.

Returns:A pygame rect.
get_starting_height() → int

Get the starting layer height of this element. (i.e. the layer we start placing it on above it's container, it may use more layers above this layer)

Returns:an integer representing the starting layer height.
get_top_layer() → int

Assuming we have correctly calculated the 'thickness' of it, this method will return the top of this element.

Return int:An integer representing the current highest layer being used by this element.
hide()

Hides the widget, which means the widget will not get drawn and will not process events. Clear hovered state.

hover_point(hover_x: float, hover_y: float) → bool

Test if a given point counts as 'hovering' this UI element. Normally that is a straightforward matter of seeing if a point is inside the rectangle. Occasionally it will also check if we are in a wider zone around a UI element once it is already active, this makes it easier to move scroll bars and the like.

Parameters:
  • hover_x -- The x (horizontal) position of the point.
  • hover_y -- The y (vertical) position of the point.
Returns:

Returns True if we are hovering this element.

join_focus_sets(element: pygame_gui.core.ui_element.UIElement)

Join this element's focus set with another's.

Parameters:element -- The other element whose focus set we are joining with.
kill()

Overriding regular sprite kill() method to remove the element from it's container.

on_fresh_drawable_shape_ready()

Called when our drawable shape has finished rebuilding the active surface. This is needed because sometimes we defer rebuilding until a more advantageous (read quieter) moment.

on_hovered()

A stub to override. Called when this UI element first enters the 'hovered' state.

on_locale_changed()

Called for each element when the locale is changed on their UIManager

on_unhovered()

A stub to override. Called when this UI element leaves the 'hovered' state.

process_event(event: pygame.event.Event) → bool

A stub to override. Gives UI Elements access to pygame events.

Parameters:event -- The event to process.
Returns:Should return True if this element makes use of this event.
rebuild()

Takes care of rebuilding this element. Most derived elements are going to override this, and hopefully call the super() class method.

rebuild_from_changed_theme_data()

A stub to override when we want to rebuild from theme data.

remove_element_from_focus_set(element)

remove an element from this sets focus group.

Parameters:element -- The element to remove.
set_dimensions(dimensions: Union[pygame.math.Vector2, Tuple[int, int], Tuple[float, float]])

Method to directly set the dimensions of an element.

NOTE: Using this on elements inside containers with non-default anchoring arrangements may make a mess of them.

Parameters:dimensions -- The new dimensions to set.
set_focus_set(focus_set: Optional[Set[UIElement]])

Set the focus set to a specific set of elements.

Parameters:focus_set -- The focus set to set.
set_image(new_image: Optional[pygame.Surface])

This used to be the way to set the proper way to set the .image property of a UIElement (inherited from pygame.Sprite), but it is intended for internal use in the library - not for adding actual images/pictures on UIElements. As such I've renamed the original function to make it protected and not part of the interface and deprecated this one for most elements.

Returns:
set_position(position: Union[pygame.math.Vector2, Tuple[int, int], Tuple[float, float]])

Method to directly set the absolute screen rect position of an element.

Parameters:position -- The new position to set.
set_relative_position(position: Union[pygame.math.Vector2, Tuple[int, int], Tuple[float, float]])

Method to directly set the relative rect position of an element.

Parameters:position -- The new position to set.
set_visual_debug_mode(activate_mode: bool)

Enables a debug mode for the element which displays layer information on top of it in a tiny font.

Parameters:activate_mode -- True or False to enable or disable the mode.
show()

Shows the widget, which means the widget will get drawn and will process events.

unfocus()

A stub to override. Called when we stop focusing this UI element.

update(time_delta: float)

Updates this element's drawable shape, if it has one.

Parameters:time_delta -- The time passed between frames, measured in seconds.
update_containing_rect_position()

Updates the position of this element based on the position of it's container. Usually called when the container has moved.

update_theming(new_theming_data: str)

Update the theming for this element using the most specific ID assigned to it.

If you have not given this element a unique ID, this function will also update the theming of other elements of this theming class or of this element type.

Parameters:new_theming_data -- the new theming data in a json string
while_hovering(time_delta: float, mouse_pos: pygame.math.Vector2)

A stub method to override. Called when this UI element is currently hovered.

Parameters:
  • time_delta -- A float, the time in seconds between the last call to this function and now (roughly).
  • mouse_pos -- The current position of the mouse as 2D Vector.

pygame_gui.core.ui_font_dictionary module

class pygame_gui.core.ui_font_dictionary.DefaultFontData(size: int, name: str, style: str, regular_file_name: str, bold_file_name: str, italic_file_name: str, bold_italic_file_name: str)

Bases: object

Data class to wrap up all the data for a default font. Used now that we have multiple default fonts for different locales.

class pygame_gui.core.ui_font_dictionary.UIFontDictionary(resource_loader: pygame_gui.core.resource_loaders.IResourceLoader, locale: str)

Bases: pygame_gui.core.interfaces.font_dictionary_interface.IUIFontDictionaryInterface

The font dictionary is used to store all the fonts that have been loaded into the UI system.

add_font_path(font_name: str, font_path: Union[str, pygame_gui.core.utility.PackageResource], bold_path: Union[str, pygame_gui.core.utility.PackageResource, None] = None, italic_path: Union[str, pygame_gui.core.utility.PackageResource, None] = None, bold_italic_path: Union[str, pygame_gui.core.utility.PackageResource, None] = None)

Adds paths to different font files for a font name.

Parameters:
  • font_name -- The name to assign to these font files.
  • font_path -- The path to the font's file with no particular style.
  • bold_path -- The path to the font's file with a bold style.
  • italic_path -- The path to the font's file with an italic style.
  • bold_italic_path -- The path to the font's file with a bold and an italic style.
check_font_preloaded(font_id: str) → bool

Check if a font is already preloaded or not.

Parameters:font_id -- The ID of the font to check for
Returns:True or False.
convert_html_to_point_size(html_size: float) → int

Takes in a HTML style font size and converts it into a point font size.

Parameters:html_size -- Size in HTML style.
Return int:A 'point' font size we can use with pygame.freetype
create_font_id(font_size: int, font_name: str, bold: bool, italic: bool) → str

Create an id for a particularly styled and sized font from those characteristics.

Parameters:
  • font_size -- The size of the font.
  • font_name -- The name of the font.
  • bold -- Whether the font is bold styled or not.
  • italic -- Whether the font is italic styled or not.
Return str:

The finished font id.

ensure_debug_font_loaded()

Ensure the font we use for debugging purposes is loaded. Generally called after we start a debugging mode.

find_font(font_size: int, font_name: str, bold: bool = False, italic: bool = False) → _freetype.Font

Find a loaded font from the font dictionary. Will load a font if it does not already exist and we have paths to the needed files, however it will issue a warning after doing so because dynamic file loading is normally a bad idea as you will get frame rate hitches while the running program waits for the font to load.

Instead it's best to preload all your needed files at another time in your program when you have more control over the user experience.

Parameters:
  • font_size -- The size of the font to find.
  • font_name -- The name of the font to find.
  • bold -- Whether the font is bold or not.
  • italic -- Whether the font is italic or not.
Return pygame.freetype.Font:
 

Returns either the font we asked for, or the default font.

find_font_resource(font_size: int, font_name: str, bold: bool = False, italic: bool = False) → pygame_gui.core.utility.FontResource

Find a loaded font resource from the font dictionary. Will load a font if it does not already exist and we have paths to the needed files, however it will issue a warning after doing so because dynamic file loading is normally a bad idea as you will get frame rate hitches while the running program waits for the font to load.

Instead it's best to preload all your needed files at another time in your program when you have more control over the user experience.

Parameters:
  • font_size -- The size of the font to find.
  • font_name -- The name of the font to find.
  • bold -- Whether the font is bold or not.
  • italic -- Whether the font is italic or not.
Return FontResource:
 

Returns either the font resource we asked for, or the default font.

get_default_font() → _freetype.Font

Grab the default font.

Returns:The default font.
preload_font(font_size: int, font_name: str, bold: bool = False, italic: bool = False, force_immediate_load: bool = False)

Lets us load a font at a particular size and style before we use it. While you can get away with relying on dynamic font loading during development, it is better to eventually pre-load all your font data at a controlled time, which is where this method comes in.

Parameters:
  • font_size -- The size of the font to load.
  • font_name -- The name of the font to load.
  • bold -- Whether the font is bold styled or not.
  • italic -- Whether the font is italic styled or not.
  • force_immediate_load -- resource loading setup to immediately load the font on the main thread.
print_unused_loaded_fonts()

Can be called to check if the UI is loading any fonts that we haven't used by the point this function is called. If a font is truly unused then we can remove it from our loading and potentially speed up the overall loading of the program.

This is not a foolproof check because this function could easily be called before we have explored all the code paths in a project that may use fonts.

set_locale(new_locale: str)

This may change the default font.

Parameters:new_locale -- The new locale to set, a two letter country code ISO 639-1

pygame_gui.core.ui_shadow module

class pygame_gui.core.ui_shadow.ShadowGenerator

Bases: object

A class to generate surfaces that work as a 'shadow' for rectangular UI elements. Base shadow surface are generated with an algorithm, then when one is requested at a specific size the closest pre-generated shadow surface is picked and then scaled to the exact size requested.

By default it creates a four base shadows in a small range of sizes. If you find the shadow appearance unsatisfactory then it is possible to create more closer to the size of the elements you are having trouble with.

clear_short_term_caches()

Empties short term caches so we aren't hanging on to so many surfaces.

create_new_ellipse_shadow(width: int, height: int, shadow_width_param: int, aa_amount: int = 4) → pygame.Surface

Creates a ellipse shaped shadow surface at the specified size and stores it for later use.

Parameters:
  • width -- The width of the shadow to create.
  • height -- The height of the shadow to create.
  • shadow_width_param -- The width of the shadowed edge.
  • aa_amount -- The amount of anti-aliasing to use, defaults to 4.
create_new_rectangle_shadow(width: int, height: int, shadow_width_param: int, corner_radius_param: int) → Optional[pygame.Surface]

Creates a rectangular shadow surface at the specified size and stores it for later use.

Parameters:
  • width -- The width of the base shadow to create.
  • height -- The height of the base shadow to create.
  • shadow_width_param -- The width of the shadowed edge.
  • corner_radius_param -- The radius of the rectangular shadow's corners.
create_shadow_corners(shadow_width_param: int, corner_radius_param: int, aa_amount=4) → Dict[str, pygame.Surface]

Create corners for our rectangular shadows. These can be used across many sizes of shadow with the same shadow width and corner radius.

Parameters:
  • shadow_width_param -- Width of the shadow.
  • corner_radius_param -- Corner radius of the shadow.
  • aa_amount -- Anti-aliasing amount. Defaults to 4x.
find_closest_shadow_scale_to_size(size: Tuple[int, int], shadow_width: int = 2, shape: str = 'rectangle', corner_radius: int = 2) → Optional[pygame.Surface]

This function searches through our dictionary of created shadows, grabs the closest one to the size we request and then scales that shadow to the exact size we need.

Parameters:
  • size -- The size of the element we are finding a shadow for.
  • shadow_width -- The width of the shadow to find.
  • shape -- The shape of the shadow to find.
  • corner_radius -- The radius of the corners if this is a rectangular shadow.
Returns:

The shadow surface we asked for scaled to the size we requested, or None if no shadows exist.

pygame_gui.core.ui_window_stack module

class pygame_gui.core.ui_window_stack.UIWindowStack(window_resolution: Tuple[int, int], root_container: pygame_gui.core.interfaces.container_interface.IUIContainerInterface)

Bases: pygame_gui.core.interfaces.window_stack_interface.IUIWindowStackInterface

A class for managing a stack of GUI windows so that only one is 'in front' at a time and the rest are sorted based on the last time they were interacted with/created.

Parameters:
  • window_resolution -- The resolution of the OS window.
  • root_container -- The root container for the whole UI.
add_new_window(window: pygame_gui.core.interfaces.window_interface.IWindowInterface)

Adds a window to the top of the stack.

Parameters:window -- The window to add.
clear()

Empties the whole stack removing and killing all windows.

get_stack() → List[pygame_gui.core.interfaces.window_interface.IWindowInterface]

Return the internal window stack directly.

Returns:a list of Windows
is_window_at_top(window: pygame_gui.core.interfaces.window_interface.IWindowInterface) → bool

Checks if a window is at the top of the window stack or not.

Parameters:window -- The window to check.
Returns:returns True if this window is at the top of the stack.
move_window_to_front(window_to_front: pygame_gui.core.interfaces.window_interface.IWindowInterface)

Moves the passed in window to the top of the window stack and resorts the other windows to deal with the change.

Parameters:window_to_front -- the window to move to the front.
remove_window(window_to_remove: pygame_gui.core.interfaces.window_interface.IWindowInterface)

Removes a window from the stack and resorts the remaining windows to adjust for it's absence.

Parameters:window_to_remove -- the window to remove.

Module contents

class pygame_gui.core.UIAppearanceTheme(resource_loader: pygame_gui.core.resource_loaders.IResourceLoader, locale: str)

Bases: pygame_gui.core.interfaces.appearance_theme_interface.IUIAppearanceThemeInterface

The Appearance Theme class handles all the data that styles and generally dictates the appearance of UI elements across the whole UI.

The styling is split into four general areas:

  • colours - spelled in the British English fashion with a 'u'.
  • font - specifying a font to use for a UIElement where that is a relevant consideration.
  • images - describing any images to be used in a UIElement.
  • misc - covering all other types of data and stored as strings.

To change the theming for the UI you normally specify a theme file when creating the UIManager. For more information on theme files see the specific documentation elsewhere.

build_all_combined_ids(element_ids: Union[None, List[str]], class_ids: Union[None, List[Optional[str]]], object_ids: Union[None, List[Optional[str]]]) → List[str]

Construct a list of combined element ids from the element's various accumulated ids.

Parameters:
  • element_ids -- All the ids of elements this element is contained within.
  • class_ids -- All the ids of 'classes' that this element is contained within.
  • object_ids -- All the ids of objects this element is contained within.
Returns:

A list of IDs that reference this element in order of decreasing specificity.

check_need_to_reload() → bool

Check if we need to reload our theme file because it's been modified. If so, trigger a reload and return True so that the UIManager can trigger elements to rebuild from the theme data.

Return bool:True if we need to reload elements because the theme data has changed.
get_colour(colour_id: str, combined_element_ids: List[str] = None) → pygame.Color

Uses data about a UI element and a specific ID to find a colour from our theme.

Parameters:
  • combined_element_ids -- A list of IDs representing an element's location in a hierarchy of elements.
  • colour_id -- The id for the specific colour we are looking for.
Return pygame.Color:
 

A pygame colour.

get_colour_or_gradient(colour_id: str, combined_ids: List[str] = None) → Union[pygame.Color, pygame_gui.core.interfaces.colour_gradient_interface.IColourGradientInterface]

Uses data about a UI element and a specific ID to find a colour, or a gradient, from our theme. Use this function if the UIElement can handle either type.

Parameters:
  • combined_ids -- A list of IDs representing an element's location in a hierarchy of elements.
  • colour_id -- The id for the specific colour we are looking for.
Return pygame.Color or ColourGradient:
 

A colour or a gradient object.

get_font(combined_element_ids: List[str]) → _freetype.Font

Uses some data about a UIElement to get a font object.

Parameters:combined_element_ids -- A list of IDs representing an element's location in a interleaved hierarchy of elements.
Return pygame.freetype.Font:
 A pygame font object.
get_font_dictionary() → pygame_gui.core.interfaces.font_dictionary_interface.IUIFontDictionaryInterface

Lets us grab the font dictionary, which is created by the theme object, so we can access it directly.

Returns:The font dictionary.
get_font_info(combined_element_ids: List[str]) → Dict[str, Any]

Uses some data about a UIElement to get font data as dictionary

Parameters:combined_element_ids -- A list of IDs representing an element's location in a interleaved hierarchy of elements.
Return dictionary:
 Data about the font requested
get_image(image_id: str, combined_element_ids: List[str]) → pygame.Surface

Will raise an exception if no image with the ids specified is found. UI elements that have an optional image display will need to handle the exception.

Parameters:
  • combined_element_ids -- A list of IDs representing an element's location in a hierarchy of elements.
  • image_id -- The id identifying the particular image spot in the UI we are looking for an image to add to.
Returns:

A pygame.surface.Surface

get_misc_data(misc_data_id: str, combined_element_ids: List[str]) → Union[str, Dict[KT, VT]]

Uses data about a UI element and a specific ID to try and find a piece of miscellaneous theming data. Raises an exception if it can't find the data requested, UI elements requesting optional data will need to handle this exception.

Parameters:
  • combined_element_ids -- A list of IDs representing an element's location in a hierarchy of elements.
  • misc_data_id -- The id for the specific piece of miscellaneous data we are looking for.
Return Any:

Returns a string or a Dict

load_theme(file_path: Union[str, os.PathLike, _io.StringIO, pygame_gui.core.utility.PackageResource])

Loads a theme file, and currently, all associated data like fonts and images required by the theme.

Parameters:file_path -- The path to the theme we want to load.
reload_theming()

We need to load our theme file to see if anything expensive has changed, if so trigger it to reload/rebuild.

set_locale(locale: str)

Set the locale used in the appearance theme.

Parameters:locale -- a two letter ISO country code.
update_caching(time_delta: float)

Updates the various surface caches.

update_single_element_theming(element_name: str, new_theming_data: str)

Update theming data, via string - for a single element. :param element_name: :param new_theming_data: :return:

update_theming(new_theming_data: str, rebuild_all: bool = True)

Update theming data, via string - for the whole UI.

Parameters:
  • new_theming_data --
  • rebuild_all --
Returns:

class pygame_gui.core.UIContainer(relative_rect: pygame.Rect, manager: pygame_gui.core.interfaces.manager_interface.IUIManagerInterface, *, starting_height: int = 1, is_window_root_container: bool = False, container: Optional[pygame_gui.core.interfaces.container_interface.IContainerLikeInterface] = None, parent_element: Optional[pygame_gui.core.ui_element.UIElement] = None, object_id: Union[pygame_gui.core.ui_element.ObjectID, str, None] = None, anchors: Optional[Dict[str, str]] = None, visible: int = 1)

Bases: pygame_gui.core.ui_element.UIElement, pygame_gui.core.interfaces.container_interface.IUIContainerInterface, pygame_gui.core.interfaces.container_interface.IContainerLikeInterface

A UI Container holds any number of other UI elements inside of a rectangle. When we move the UIContainer all the UI elements contained within it can be moved as well.

This class helps us make UI Windows, but likely will have wider uses as well as the GUI system develops.

Parameters:
  • relative_rect -- A pygame.Rect whose position is relative to whatever UIContainer it is inside of, if any.
  • manager -- The UIManager that manages this UIElement.
  • starting_height -- The starting layer height for this element above it's container.
  • is_window_root_container -- True/False flag for whether this container is the root container for a UI window.
  • container -- The UIContainer that this UIElement is contained within.
  • parent_element -- The element this element 'belongs to' in the theming hierarchy.
  • object_id -- A custom defined ID for fine tuning of theming.
  • anchors -- A dictionary describing what this element's relative_rect is relative to.
  • visible -- Whether the container and its children are visible by default. Warning - it's parent container visibility may override this.
add_element(element: pygame_gui.core.interfaces.element_interface.IUIElementInterface)

Add a UIElement to the container. The UI's relative_rect parameter will be relative to this container.

Parameters:element -- A UIElement to add to this container.
calc_add_element_changes_thickness(element: pygame_gui.core.interfaces.element_interface.IUIElementInterface)

This function checks if a single added element will increase the containers thickness and if so updates containers recursively.

Parameters:element -- the element to check.
change_layer(new_layer: int)

Change the layer of this container. Layers are used by the GUI to control the order in which things are drawn and which things should currently be interactive (so you can't interact with things behind other things).

This particular method is most often used to shift the visible contents of a window in front of any others when it is moved to the front of the window stack.

Parameters:new_layer -- The layer to move our container to.
check_hover(time_delta: float, hovered_higher_element: bool) → bool

A method that helps us to determine which, if any, UI Element is currently being hovered by the mouse.

Parameters:
  • time_delta -- A float, the time in seconds between the last call to this function and now (roughly).
  • hovered_higher_element -- A boolean, representing whether we have already hovered a 'higher' element.
Returns:

A boolean that is true if we have hovered a UI element, either just now or before this method.

clear()

Removes and kills all the UI elements inside this container.

disable()

Disables all elements in the container so they are no longer interactive.

enable()

Enables all elements in the container so they are interactive again.

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

Implements the container interface. In this case we just return this since it is a container.

Returns:This container.
get_rect() → pygame.Rect

Access to the container's rect

Returns:a pygame rectangle
get_size() → Tuple[int, int]

Get the container's pixel size.

Returns:the pixel size as tuple [x, y]
get_thickness() → int

Get the container's layer thickness.

Returns:the thickness as an integer.
get_top_layer() → int

Assuming we have correctly calculated the 'thickness' of this container, this method will return the 'highest' layer in the LayeredDirty UI Group.

Returns:An integer representing the current highest layer being used by this container.
hide()

Hides the container, which means the container will not get drawn and will not process events. Should also hide all the children elements and containers. If the container was hidden before - ignore.

kill()

Overrides the standard kill method of UI Elements (and pygame sprites beyond that) to also call the kill method on all contained UI Elements.

on_anchor_target_changed(target: pygame_gui.core.ui_element.UIElement)

Update the contents of this container that one of their layout anchors may have moved, or been resized.

Parameters:target -- the UI element that has been benn moved or resized.
recalculate_container_layer_thickness()

This function will iterate through the elements in our container and determine the maximum 'height' that they reach in the 'layer stack'. We then use that to determine the overall 'thickness' of this container. The thickness value is used to determine where to place overlapping windows in the layers

remove_element(element: pygame_gui.core.interfaces.element_interface.IUIElementInterface)

Remove a UIElement from this container.

Parameters:element -- A UIElement to remove from this container.
set_dimensions(dimensions: Union[pygame.math.Vector2, Tuple[int, int], Tuple[float, float]])

Set the dimension of this container and update the positions of elements within it accordingly.

Parameters:dimensions -- the new dimensions.
set_position(position: Union[pygame.math.Vector2, Tuple[int, int], Tuple[float, float]])

Set the absolute position of this container - it is usually less chaotic to deal with setting relative positions.

Parameters:position -- the new absolute position to set.
set_relative_position(position: Union[pygame.math.Vector2, Tuple[int, int], Tuple[float, float]])

Set the position of this container, relative to the container it is within.

Parameters:position -- the new relative position to set.
show()

Shows the container, which means the container will get drawn and will process events. Should also show all the children elements and containers. If the container was visible before - ignore.

update_containing_rect_position()

This function is called when we move the container to update all the contained UI Elements to move as well.

class pygame_gui.core.UIElement(relative_rect: Union[pygame.Rect, Tuple[int, int, int, int]], manager: Optional[pygame_gui.core.interfaces.manager_interface.IUIManagerInterface], container: Optional[pygame_gui.core.interfaces.container_interface.IContainerLikeInterface], *, starting_height: int, layer_thickness: int, anchors: Dict[str, Union[str, UIElement]] = None, visible: int = 1)

Bases: pygame_gui.core.layered_gui_group.GUISprite, pygame_gui.core.interfaces.element_interface.IUIElementInterface

A base class for UI elements. You shouldn't create UI Element objects, instead all UI Element classes should derive from this class. Inherits from pygame.sprite.Sprite.

Parameters:
  • relative_rect -- A rectangle shape of the UI element, the position is relative to the element's container.
  • manager -- The UIManager that manages this UIElement.
  • container -- A container that this element is contained in.
  • starting_height -- Used to record how many layers above it's container this element should be. Normally 1.
  • layer_thickness -- Used to record how 'thick' this element is in layers. Normally 1.
  • anchors -- A dictionary describing what this element's relative_rect is relative to.
  • visible -- Whether the element is visible by default. Warning - container visibility may override this.
can_hover() → bool

A stub method to override. Called to test if this method can be hovered.

change_layer(new_layer: int)

Changes the layer this element is on.

Parameters:new_layer -- The layer to change this element to.
check_hover(time_delta: float, hovered_higher_element: bool) → bool

A method that helps us to determine which, if any, UI Element is currently being hovered by the mouse.

Parameters:
  • time_delta -- A float, the time in seconds between the last call to this function and now (roughly).
  • hovered_higher_element -- A boolean, representing whether we have already hovered a 'higher' element.
Return bool:

A boolean that is true if we have hovered a UI element, either just now or before this method.

disable()

Disables elements so they are no longer interactive. This is just a default fallback implementation for elements that don't define their own.

Elements should handle their own enabling and disabling.

enable()

Enables elements so they are interactive again. This is just a default fallback implementation for elements that don't define their own.

Elements should handle their own enabling and disabling.

focus()

A stub to override. Called when we focus this UI element.

get_abs_rect() → pygame.Rect

The absolute positioning rect.

Returns:A pygame rect.
get_anchor_targets() → list

Get any anchor targets this element has so we can update them when their targets change :return: the list of anchor targets.

get_element_ids() → List[str]

A list of all the element IDs in this element's theming/event hierarchy.

Returns:a list of strings, one ofr each element in the hierarchy.
get_focus_set() → Set[pygame_gui.core.ui_element.UIElement]

Return the set of elements to focus when we focus this element.

get_image_clipping_rect() → Optional[pygame.Rect]

Obtain the current image clipping rect.

Returns:The current clipping rect. May be None.
get_relative_rect() → pygame.Rect

The relative positioning rect.

Returns:A pygame rect.
get_starting_height() → int

Get the starting layer height of this element. (i.e. the layer we start placing it on above it's container, it may use more layers above this layer)

Returns:an integer representing the starting layer height.
get_top_layer() → int

Assuming we have correctly calculated the 'thickness' of it, this method will return the top of this element.

Return int:An integer representing the current highest layer being used by this element.
hide()

Hides the widget, which means the widget will not get drawn and will not process events. Clear hovered state.

hover_point(hover_x: float, hover_y: float) → bool

Test if a given point counts as 'hovering' this UI element. Normally that is a straightforward matter of seeing if a point is inside the rectangle. Occasionally it will also check if we are in a wider zone around a UI element once it is already active, this makes it easier to move scroll bars and the like.

Parameters:
  • hover_x -- The x (horizontal) position of the point.
  • hover_y -- The y (vertical) position of the point.
Returns:

Returns True if we are hovering this element.

join_focus_sets(element: pygame_gui.core.ui_element.UIElement)

Join this element's focus set with another's.

Parameters:element -- The other element whose focus set we are joining with.
kill()

Overriding regular sprite kill() method to remove the element from it's container.

on_fresh_drawable_shape_ready()

Called when our drawable shape has finished rebuilding the active surface. This is needed because sometimes we defer rebuilding until a more advantageous (read quieter) moment.

on_hovered()

A stub to override. Called when this UI element first enters the 'hovered' state.

on_locale_changed()

Called for each element when the locale is changed on their UIManager

on_unhovered()

A stub to override. Called when this UI element leaves the 'hovered' state.

process_event(event: pygame.event.Event) → bool

A stub to override. Gives UI Elements access to pygame events.

Parameters:event -- The event to process.
Returns:Should return True if this element makes use of this event.
rebuild()

Takes care of rebuilding this element. Most derived elements are going to override this, and hopefully call the super() class method.

rebuild_from_changed_theme_data()

A stub to override when we want to rebuild from theme data.

remove_element_from_focus_set(element)

remove an element from this sets focus group.

Parameters:element -- The element to remove.
set_dimensions(dimensions: Union[pygame.math.Vector2, Tuple[int, int], Tuple[float, float]])

Method to directly set the dimensions of an element.

NOTE: Using this on elements inside containers with non-default anchoring arrangements may make a mess of them.

Parameters:dimensions -- The new dimensions to set.
set_focus_set(focus_set: Optional[Set[UIElement]])

Set the focus set to a specific set of elements.

Parameters:focus_set -- The focus set to set.
set_image(new_image: Optional[pygame.Surface])

This used to be the way to set the proper way to set the .image property of a UIElement (inherited from pygame.Sprite), but it is intended for internal use in the library - not for adding actual images/pictures on UIElements. As such I've renamed the original function to make it protected and not part of the interface and deprecated this one for most elements.

Returns:
set_position(position: Union[pygame.math.Vector2, Tuple[int, int], Tuple[float, float]])

Method to directly set the absolute screen rect position of an element.

Parameters:position -- The new position to set.
set_relative_position(position: Union[pygame.math.Vector2, Tuple[int, int], Tuple[float, float]])

Method to directly set the relative rect position of an element.

Parameters:position -- The new position to set.
set_visual_debug_mode(activate_mode: bool)

Enables a debug mode for the element which displays layer information on top of it in a tiny font.

Parameters:activate_mode -- True or False to enable or disable the mode.
show()

Shows the widget, which means the widget will get drawn and will process events.

unfocus()

A stub to override. Called when we stop focusing this UI element.

update(time_delta: float)

Updates this element's drawable shape, if it has one.

Parameters:time_delta -- The time passed between frames, measured in seconds.
update_containing_rect_position()

Updates the position of this element based on the position of it's container. Usually called when the container has moved.

update_theming(new_theming_data: str)

Update the theming for this element using the most specific ID assigned to it.

If you have not given this element a unique ID, this function will also update the theming of other elements of this theming class or of this element type.

Parameters:new_theming_data -- the new theming data in a json string
while_hovering(time_delta: float, mouse_pos: pygame.math.Vector2)

A stub method to override. Called when this UI element is currently hovered.

Parameters:
  • time_delta -- A float, the time in seconds between the last call to this function and now (roughly).
  • mouse_pos -- The current position of the mouse as 2D Vector.
class pygame_gui.core.ObjectID(object_id, class_id)

Bases: tuple

class_id

Alias for field number 1

object_id

Alias for field number 0

class pygame_gui.core.UIFontDictionary(resource_loader: pygame_gui.core.resource_loaders.IResourceLoader, locale: str)

Bases: pygame_gui.core.interfaces.font_dictionary_interface.IUIFontDictionaryInterface

The font dictionary is used to store all the fonts that have been loaded into the UI system.

add_font_path(font_name: str, font_path: Union[str, pygame_gui.core.utility.PackageResource], bold_path: Union[str, pygame_gui.core.utility.PackageResource, None] = None, italic_path: Union[str, pygame_gui.core.utility.PackageResource, None] = None, bold_italic_path: Union[str, pygame_gui.core.utility.PackageResource, None] = None)

Adds paths to different font files for a font name.

Parameters:
  • font_name -- The name to assign to these font files.
  • font_path -- The path to the font's file with no particular style.
  • bold_path -- The path to the font's file with a bold style.
  • italic_path -- The path to the font's file with an italic style.
  • bold_italic_path -- The path to the font's file with a bold and an italic style.
check_font_preloaded(font_id: str) → bool

Check if a font is already preloaded or not.

Parameters:font_id -- The ID of the font to check for
Returns:True or False.
convert_html_to_point_size(html_size: float) → int

Takes in a HTML style font size and converts it into a point font size.

Parameters:html_size -- Size in HTML style.
Return int:A 'point' font size we can use with pygame.freetype
create_font_id(font_size: int, font_name: str, bold: bool, italic: bool) → str

Create an id for a particularly styled and sized font from those characteristics.

Parameters:
  • font_size -- The size of the font.
  • font_name -- The name of the font.
  • bold -- Whether the font is bold styled or not.
  • italic -- Whether the font is italic styled or not.
Return str:

The finished font id.

ensure_debug_font_loaded()

Ensure the font we use for debugging purposes is loaded. Generally called after we start a debugging mode.

find_font(font_size: int, font_name: str, bold: bool = False, italic: bool = False) → _freetype.Font

Find a loaded font from the font dictionary. Will load a font if it does not already exist and we have paths to the needed files, however it will issue a warning after doing so because dynamic file loading is normally a bad idea as you will get frame rate hitches while the running program waits for the font to load.

Instead it's best to preload all your needed files at another time in your program when you have more control over the user experience.

Parameters:
  • font_size -- The size of the font to find.
  • font_name -- The name of the font to find.
  • bold -- Whether the font is bold or not.
  • italic -- Whether the font is italic or not.
Return pygame.freetype.Font:
 

Returns either the font we asked for, or the default font.

find_font_resource(font_size: int, font_name: str, bold: bool = False, italic: bool = False) → pygame_gui.core.utility.FontResource

Find a loaded font resource from the font dictionary. Will load a font if it does not already exist and we have paths to the needed files, however it will issue a warning after doing so because dynamic file loading is normally a bad idea as you will get frame rate hitches while the running program waits for the font to load.

Instead it's best to preload all your needed files at another time in your program when you have more control over the user experience.

Parameters:
  • font_size -- The size of the font to find.
  • font_name -- The name of the font to find.
  • bold -- Whether the font is bold or not.
  • italic -- Whether the font is italic or not.
Return FontResource:
 

Returns either the font resource we asked for, or the default font.

get_default_font() → _freetype.Font

Grab the default font.

Returns:The default font.
preload_font(font_size: int, font_name: str, bold: bool = False, italic: bool = False, force_immediate_load: bool = False)

Lets us load a font at a particular size and style before we use it. While you can get away with relying on dynamic font loading during development, it is better to eventually pre-load all your font data at a controlled time, which is where this method comes in.

Parameters:
  • font_size -- The size of the font to load.
  • font_name -- The name of the font to load.
  • bold -- Whether the font is bold styled or not.
  • italic -- Whether the font is italic styled or not.
  • force_immediate_load -- resource loading setup to immediately load the font on the main thread.
print_unused_loaded_fonts()

Can be called to check if the UI is loading any fonts that we haven't used by the point this function is called. If a font is truly unused then we can remove it from our loading and potentially speed up the overall loading of the program.

This is not a foolproof check because this function could easily be called before we have explored all the code paths in a project that may use fonts.

set_locale(new_locale: str)

This may change the default font.

Parameters:new_locale -- The new locale to set, a two letter country code ISO 639-1
class pygame_gui.core.ShadowGenerator

Bases: object

A class to generate surfaces that work as a 'shadow' for rectangular UI elements. Base shadow surface are generated with an algorithm, then when one is requested at a specific size the closest pre-generated shadow surface is picked and then scaled to the exact size requested.

By default it creates a four base shadows in a small range of sizes. If you find the shadow appearance unsatisfactory then it is possible to create more closer to the size of the elements you are having trouble with.

clear_short_term_caches()

Empties short term caches so we aren't hanging on to so many surfaces.

create_new_ellipse_shadow(width: int, height: int, shadow_width_param: int, aa_amount: int = 4) → pygame.Surface

Creates a ellipse shaped shadow surface at the specified size and stores it for later use.

Parameters:
  • width -- The width of the shadow to create.
  • height -- The height of the shadow to create.
  • shadow_width_param -- The width of the shadowed edge.
  • aa_amount -- The amount of anti-aliasing to use, defaults to 4.
create_new_rectangle_shadow(width: int, height: int, shadow_width_param: int, corner_radius_param: int) → Optional[pygame.Surface]

Creates a rectangular shadow surface at the specified size and stores it for later use.

Parameters:
  • width -- The width of the base shadow to create.
  • height -- The height of the base shadow to create.
  • shadow_width_param -- The width of the shadowed edge.
  • corner_radius_param -- The radius of the rectangular shadow's corners.
create_shadow_corners(shadow_width_param: int, corner_radius_param: int, aa_amount=4) → Dict[str, pygame.Surface]

Create corners for our rectangular shadows. These can be used across many sizes of shadow with the same shadow width and corner radius.

Parameters:
  • shadow_width_param -- Width of the shadow.
  • corner_radius_param -- Corner radius of the shadow.
  • aa_amount -- Anti-aliasing amount. Defaults to 4x.
find_closest_shadow_scale_to_size(size: Tuple[int, int], shadow_width: int = 2, shape: str = 'rectangle', corner_radius: int = 2) → Optional[pygame.Surface]

This function searches through our dictionary of created shadows, grabs the closest one to the size we request and then scales that shadow to the exact size we need.

Parameters:
  • size -- The size of the element we are finding a shadow for.
  • shadow_width -- The width of the shadow to find.
  • shape -- The shape of the shadow to find.
  • corner_radius -- The radius of the corners if this is a rectangular shadow.
Returns:

The shadow surface we asked for scaled to the size we requested, or None if no shadows exist.

class pygame_gui.core.UIWindowStack(window_resolution: Tuple[int, int], root_container: pygame_gui.core.interfaces.container_interface.IUIContainerInterface)

Bases: pygame_gui.core.interfaces.window_stack_interface.IUIWindowStackInterface

A class for managing a stack of GUI windows so that only one is 'in front' at a time and the rest are sorted based on the last time they were interacted with/created.

Parameters:
  • window_resolution -- The resolution of the OS window.
  • root_container -- The root container for the whole UI.
add_new_window(window: pygame_gui.core.interfaces.window_interface.IWindowInterface)

Adds a window to the top of the stack.

Parameters:window -- The window to add.
clear()

Empties the whole stack removing and killing all windows.

get_stack() → List[pygame_gui.core.interfaces.window_interface.IWindowInterface]

Return the internal window stack directly.

Returns:a list of Windows
is_window_at_top(window: pygame_gui.core.interfaces.window_interface.IWindowInterface) → bool

Checks if a window is at the top of the window stack or not.

Parameters:window -- The window to check.
Returns:returns True if this window is at the top of the stack.
move_window_to_front(window_to_front: pygame_gui.core.interfaces.window_interface.IWindowInterface)

Moves the passed in window to the top of the window stack and resorts the other windows to deal with the change.

Parameters:window_to_front -- the window to move to the front.
remove_window(window_to_remove: pygame_gui.core.interfaces.window_interface.IWindowInterface)

Removes a window from the stack and resorts the remaining windows to adjust for it's absence.

Parameters:window_to_remove -- the window to remove.
class pygame_gui.core.IContainerLikeInterface

Bases: object

A meta class that defines the interface for containers used by elements.

This interface lets us treat classes like UIWindows and UIPanels like containers for elements even though they actually pass this functionality off to the proper UIContainer class.

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

Gets an actual container from this container-like UI element.

hide()

Hides the container, which means the container will not get drawn and will not process events. Should also hide all the children elements. If the container was hidden before - ignore.

show()

Shows the container, which means the container will get drawn and will process events. Should also show all the children elements. If the container was visible before - ignore.

class pygame_gui.core.IWindowInterface

Bases: object

A meta class that defines the interface that the window stack uses to interface with the UIWindow class.

Interfaces like this help us evade cyclical import problems by allowing us to define the actual window class later on and have it make use of the window stack.

can_hover() → bool

Called to test if this window can be hovered.

change_layer(layer: int)

Change the drawing layer of this window.

Parameters:layer -- the new layer to move to.
check_clicked_inside_or_blocking(event: pygame.event.Event) → bool

A quick event check outside of the normal event processing so that this window is brought to the front of the window stack if we click on any of the elements contained within it.

Parameters:event -- The event to check.
Returns:returns True if the event represents a click inside this window or the window is blocking.
check_hover(time_delta: float, hovered_higher_element: bool) → bool

For the window the only hovering we care about is the edges if this is a resizable window.

Parameters:
  • time_delta -- time passed in seconds between one call to this method and the next.
  • hovered_higher_element -- Have we already hovered an element/window above this one.
get_hovering_edge_id() → str

Gets the ID of the combination of edges we are hovering for use by the cursor system.

Returns:a string containing the edge combination ID (e.g. xy,yx,xl,xr,yt,yb)
get_top_layer() → int

Returns the 'highest' layer used by this window so that we can correctly place other windows on top of it.

Returns:The top layer for this window as a number (greater numbers are higher layers).
kill()

Overrides the basic kill() method of a pygame sprite so that we also kill all the UI elements in this window, and remove if from the window stack.

on_moved_to_front()

Called when a window is moved to the front of the stack.

process_event(event: pygame.event.Event) → bool

Handles resizing & closing windows. Gives UI Windows access to pygame events. Derived windows should super() call this class if they implement their own process_event method.

Parameters:event -- The event to process.
Return bool:Return True if this element should consume this event and not pass it to the rest of the UI.
rebuild()

Rebuilds the window when the theme has changed.

rebuild_from_changed_theme_data()

Called by the UIManager to check the theming data and rebuild whatever needs rebuilding for this element when the theme data has changed.

set_blocking(state: bool)

Sets whether this window being open should block clicks to the rest of the UI or not. Defaults to False.

Parameters:state -- True if this window should block mouse clicks.
set_dimensions(dimensions: Union[pygame.math.Vector2, Tuple[int, int], Tuple[float, float]])

Set the size of this window and then re-sizes and shifts the contents of the windows container to fit the new size.

Parameters:dimensions -- The new dimensions to set.
set_display_title(new_title: str)

Set the title of the window.

Parameters:new_title -- The title to set.
set_minimum_dimensions(dimensions: Union[pygame.math.Vector2, Tuple[int, int], Tuple[float, float]])

If this window is resizable, then the dimensions we set here will be the minimum that users can change the window to. They are also used as the minimum size when 'set_dimensions' is called.

Parameters:dimensions -- The new minimum dimension for the window.
set_position(position: Union[pygame.math.Vector2, Tuple[int, int], Tuple[float, float]])

Method to directly set the absolute screen rect position of an element.

Parameters:position -- The new position to set.
set_relative_position(position: Union[pygame.math.Vector2, Tuple[int, int], Tuple[float, float]])

Method to directly set the relative rect position of an element.

Parameters:position -- The new position to set.
should_use_window_edge_resize_cursor() → bool

Returns true if this window is in a state where we should display one of the resizing cursors

Returns:True if a resizing cursor is needed.
update(time_delta: float)

A method called every update cycle of our application. Designed to be overridden by derived classes but also has a little functionality to make sure the window's layer 'thickness' is accurate and to handle window resizing.

Parameters:time_delta -- time passed in seconds between one call to this method and the next.
class pygame_gui.core.ColourGradient(angle_direction: int, colour_1: pygame.Color, colour_2: pygame.Color, colour_3: Optional[pygame.Color] = None)

Bases: pygame_gui.core.interfaces.colour_gradient_interface.IColourGradientInterface

Creates a small surface containing a smooth gradient between two or three colours.

Parameters:
  • angle_direction -- Angle direction of the gradient in degrees.
  • colour_1 -- The first colour of the gradient.
  • colour_2 -- The second colour of the gradient.
  • colour_3 -- An optional third colour for the gradient.
apply_gradient_to_surface(input_surface: pygame.Surface, rect: Optional[pygame.Rect] = None)

Applies this gradient to a specified input surface using blending multiplication. As a result this method works best when the input surface is a mostly white, stencil shape type surface.

Parameters:
  • input_surface --
  • rect -- The rectangle on the surface to apply the gradient to. If None, applies to the whole surface.
class pygame_gui.core.BlockingThreadedResourceLoader

Bases: pygame_gui.core.resource_loaders.ThreadedLoader, pygame_gui.core.resource_loaders.IResourceLoader

This loader is designed to have it's update function called once, after which it will block the main thread until all it's assigned loading is complete.

update() → Tuple[bool, float]

Updates the load process. Blocks until it is completed.

Returns:A Boolean indicating whether the load has finished, and a float indicating the load's progress (between 0.0 and 1.0).
class pygame_gui.core.IncrementalThreadedResourceLoader

Bases: pygame_gui.core.resource_loaders.ThreadedLoader, pygame_gui.core.resource_loaders.IResourceLoader

This loader is designed to have it's update function called repeatedly until it is finished.

It's useful if you want to display a loading progress bar for the UI - Though you will have to be careful not to use any assets that are still being loaded.

set_update_time_budget(budget: float)

Set the minimum amount of time to spend loading, per update loop.

Actual time spent may be somewhat over this budget as a long file load may start while we are within the budget.

NOTE: This only affects sequentially loading resources.

Parameters:budget -- A time budget in seconds. The default is 0.02 seconds.
update() → Tuple[bool, float]

Updates the load process will try to spend only as much time in here as allocated by the time budget.

Returns:A Boolean indicating whether the load has finished, and a float indicating the load's progress (between 0.0 and 1.0).
class pygame_gui.core.TextBoxLayout(input_data_queue: Deque[pygame_gui.core.text.text_layout_rect.TextLayoutRect], layout_rect: pygame.Rect, view_rect: pygame.Rect, line_spacing: float, default_font_data: Dict[str, Any], allow_split_dashes: bool = True)

Bases: object

Class to layout multiple lines of text to fit in a defined column.

The base of the 'column' rectangle is set once the data supplied has been laid out to fit in the width provided.

add_chunks_to_hover_group(link_hover_chunks: List[pygame_gui.core.text.text_layout_rect.TextLayoutRect])

Pass in a list of layout rectangles to add to a hoverable group. Usually used for hyperlinks.

Parameters:link_hover_chunks --
align_left_all_rows(x_padding)

Align all rows to the left hand side of the layout.

Parameters:x_padding -- the amount of padding to insert to on the left before the text starts.
align_right_all_rows(x_padding)

Align all rows to the right hand side of the layout.

Parameters:x_padding -- the amount of padding to insert to on the right before the text starts.
append_layout_rects(new_queue)

Add some LayoutRect's on to the end of the current layout. This should be relatively fast as we don't have to rejig everything before the additions, and some of the time don't need to redraw everything either.

This is new so there may still be some bugs to iron out.

Parameters:new_queue --
backspace_at_cursor()

Deletes a single character behind the edit cursor. Mimics a standard word processor 'backspace' operation.

blit_finalised_text_to_surf(surface: pygame.Surface)

Lets us blit a finalised text surface to an arbitrary surface. Useful for doing stuff with text effects.

Parameters:surface -- the target surface to blit onto.
clear_effects()

Clear text layout level text effect parameters.

clear_final_surface()

Clears the finalised surface.

delete_at_cursor()

Deletes a single character in front of the edit cursor. Mimics a standard word processor 'delete' operation.

delete_selected_text()

Delete the currently selected text.

finalise_to_new()

Finalises our layout to a brand new surface that this method creates.

finalise_to_surf(surface: pygame.Surface)

Take this layout, with everything positioned in the correct place and finalise it to a surface.

May be called again after changes to the layout? Update surf?

Parameters:surface -- The surface we are going to blit the contents of this layout onto.
find_cursor_position_from_click_pos(click_pos) → int

Find an edit text cursor position in the text from a click.

Here we don't set it, we just find it and return it.

Parameters:click_pos -- This is the pixel position we want to find the nearest cursor spot to.
Returns:an integer representing the character index position in the text
get_cursor_colour() → pygame.Color

Get the current colour of the editing carat/text cursor.

Returns:a pygame.Color object containing the current colour.
get_cursor_index()

Get the current character index, in the text layout's text, of the current edit cursor position.

Essentially the reverse of 'set_cursor_position()'.

get_cursor_pos_move_down_one_row(last_cursor_horiz_index)

Returns a cursor character position in the row directly above the current cursor position if possible.

get_cursor_pos_move_up_one_row(last_cursor_horiz_index)

Returns a cursor character position in the row directly above the last horizontal cursor position if possible.

horiz_center_all_rows(method='rect')

Horizontally center all rows of text in the layout. This uses 'rectangular' centering by default, which could also be called mathematical centering. Sometimes this type of centering looks wrong - e.g. for arrows, so we instead have an option to use a 'center of mass' style centering for right facing and left facing triangles.

Parameters:method -- this is an ID for the method of centering to use, for almost all cases this will be the default 'rect' style basic centering. However, if you are trying to center an arrow you might try 'right_triangle' or 'left_triangle'
insert_layout_rects(layout_rects: Deque[pygame_gui.core.text.text_layout_rect.TextLayoutRect], row_index: int, item_index: int, chunk_index: int)

Insert some new layout rectangles from a queue at specific place in the current layout. Hopefully this means we only need to redo the layout after this point... we shall see.

Warning: this is a test function, it may noit be up to date with current text layout features

Parameters:
  • layout_rects -- the new TextLayoutRects to insert.
  • row_index -- which row we are sticking them on.
  • item_index -- which chunk we are sticking them into.
  • chunk_index -- where in the chunk we are sticking them.
insert_line_break(layout_index: int, parser: Optional[pygame_gui.core.text.html_parser.HTMLParser])

Insert a line break into the text layout at a given point.

Parameters:
  • layout_index -- the character index at which to insert the line break.
  • parser -- An optional HTML parser for text styling data
insert_text(text: str, layout_index: int, parser: Optional[pygame_gui.core.text.html_parser.HTMLParser] = None)

Insert some text into the text layout at a given point. Handy when e.g. pasting a chunk of text into an existing layout.

Parameters:
  • text -- the text to insert.
  • layout_index -- the character index at which to insert the text.
  • parser -- An optional HTML parser for text styling data
redraw_other_chunks(not_these_chunks)

Useful for text effects. TODO: no idea how this will play with images? Probably badly.

Parameters:not_these_chunks -- The chunks not to redraw
Returns:
reprocess_layout_queue(layout_rect)

Re-lays out already parsed text data. Useful to call if the layout requirements have changed but the text data hasn't.

Parameters:layout_rect -- The new layout rectangle.
set_alpha(alpha: int)

Set the overall alpha level of this text box from 0 to 255. This allows us to fade text in and out of view.

Parameters:alpha -- integer from 0 to 255.
set_cursor_colour(colour: pygame.Color)

Set the colour of the editing carat/text cursor for this text layout.

Parameters:colour -- The colour to set it to.
set_cursor_from_click_pos(click_pos)

Set the edit cursor position in the text layout from a pixel position. Generally used to set the text editing cursor position from a mouse click.

Parameters:click_pos -- This is the pixel position we want the cursor to appear near to.
set_cursor_position(cursor_pos)

Set the edit cursor position in the text layout.

Parameters:cursor_pos -- This is the index of the character the cursor should appear before.
set_default_text_colour(colour)

Set the default text colour, used when no other colour is set for a portion of the text.

Parameters:colour -- the colour to use as the default text colour.
set_default_text_shadow_colour(colour)

Set the default text shadow colour, used when no other colour is set for the shadow of a portion of the text.

Parameters:colour -- the colour to use as the default text shadow colour.
set_text_selection(start_index, end_index)

Set a portion of the text layout as 'selected'. This is useful when editing chunks of text all at once (e.g. copying to a memory 'clipboard', deleting a block of text).

Parameters:
  • start_index -- the character index to start the selection area at.
  • end_index -- the character index to end the selection area at.
toggle_cursor()

Toggle the visibility of the edit cursor.

Used routinely by editable text boxes to make the cursor flash to catch user attention.

turn_off_cursor()

Makes the edit test cursor invisible.

turn_on_cursor()

Makes the edit test cursor visible.

update_text_with_new_text_end_pos(new_end_pos: int)

Sets a new end position for the text in this block and redraws it so we can display a 'typing' type effect. The text will only be displayed up to the index position set here.

Parameters:new_end_pos -- The new ending index for the text string.
vert_align_bottom_all_rows(y_padding)

Align all rows to the bottom of the layout.

Parameters:y_padding -- the amount of padding to insert below before the text starts.
vert_align_top_all_rows(y_padding)

Align all rows to the top of the layout.

Parameters:y_padding -- the amount of padding to insert above before the text starts.
vert_center_all_rows()

Vertically center all rows of text in the layout.

TODO: I expect we should have the arrow centering methods in here too.