pygame_gui.core package

Subpackages

Submodules

pygame_gui.core.colour_gradient module

class pygame_gui.core.colour_gradient.ColourGradient(angle_direction: int, colour_1: Color, colour_2: Color, colour_3: Color | None = None)

Bases: 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: Surface, rect: Rect | None = 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.colour_parser module

pygame_gui.core.colour_parser.py A Functional Based Module for the parsing of Colour Strings in pygame_gui

Use Notes:
Mostly all that one will ever need is these 5 functions
  • parse_colour_or_gradient_string: Attempt to parse a string that may be a colour or gradient into its respective value

  • is_valid_colour_string: Check if a string represents a valid pygame Color

  • is_valid_gradient_string: Check if a string represents a valid pygame_gui.core.colour_gradient.ColourGradient

  • parse_colour_string: Parse a string into a pygame Color

  • parse_gradient_string: Parse a string into a pygame_gui.core.colour_gradient.ColourGradient

The documentation for what counts as a 'Valid' colour and gradient string can be found in the Theme Guide of the pygame_gui documentation at https://pygame-gui.readthedocs.io/en/v_065/theme_guide.html

Developer Notes:
How it Works:

This module works through pairs of validating and parsing functions at the value, colour, and gradient levels Hopefully everything should be generic enough that any new colour models or representations can be easily added without much bloat or magic

Parsing A Colour:

Simply, The parsing of a colour is done by simply checking if there is any valid function cashed in the _colourParsers dictionary, then calling the paired parsing function to get its value Therefore, this system is not concrete at all, and should be extremely extensible to add any 2 functions that can validate and parse a developer-determined schema

Parsing A Gradient:

As of now, the gradient parser is implemented in such a way where it assumes that all commas outside an enclosing glyph ( Any comma not inside a (), [], or {} ) is a separator in a gradient list Generally, if creating new colour string schemas, this will break if there is a new colour which uses commas not enclosed in a glyph. This shouldn't be a problem right now, but it is worth noting as a warning in case of any additions to this parser TL,DR: Dev life will be easier if it is ensured that commas in colour schemas are inside of parentheses, brackets, or curly braces (like "rgb(20, 20, 20)")

class pygame_gui.core.colour_parser.ColourValueParserData(*args, **kwargs)

Bases: dict

class pygame_gui.core.colour_parser.NumParserType(value)

Bases: Enum

Enum for the supported value types in colour strings

pygame_gui.core.colour_parser.expand_shorthand_hex(strdata: str) str
Expand a Shorthand Hex Color
Example:

#FA2 -> #FFAA22

Parameters:

strdata (str) -- the hex string to expand

Returns:

An expanded hex string

Return type:

str

pygame_gui.core.colour_parser.get_commas_outside_enclosing_glyphs(strdata: str) List[int]
In the colour_parser module, This function is used to determine where to split gradient strings in order to get the full list of colours and the final degrees
Developer Notes:
  • Used to determine which top level commas should be used to separate gradients

  • Used with the assumption that colour values themselves do not have glyphs that are left opened

  • Used with the assumption that top level commas used to separate gradients are not within any sort of enclosing glyph

  • An enclosing glyph is like a parentheses, bracket, curly brace, or something of the sort

Parameters:

strdata (str) -- the string to check

Returns:

A list of the indices of the commas determined to be outside any enclosing parentheses

Return type:

list[int]

pygame_gui.core.colour_parser.is_valid_cmy_string(strdata: str) bool
Validate CMY Color string in the format "cmy(percentage, percentage, percentage)"
Value Parameter Descriptions:
  • percentage: either an integer value from 0 to 100 with "%" appended at the end or a float value ranging from 0 to 1

Examples:
  • "cmy(.4, .7, 80%)"

Parameters:

strdata (str) -- the cmy string to validate

Returns:

A boolean determining whether the string fits the determined cmy schema

Return type:

bool

pygame_gui.core.colour_parser.is_valid_colour_name(strdata: str)
Validate Colour name string to be recognizable by pygame_gui as a valid colour_name
As of the writing of these documentations, all colour names defined are from the CSS colours given by all major browsers, which can be found here: https://w3schools.sinsixx.com/css/css_colornames.asp.htm
All colour names are not case-sensitive, so RED, Red, and red all represent the same value
Parameters:

strdata (str) -- the colour name to validate

Returns:

A boolean determining whether strdata is recognized as a colour name and has a locatable colour value

Return type:

bool

pygame_gui.core.colour_parser.is_valid_colour_string(strdata: str) bool

Validate a colour string using the available colour string validator and parsers in pygame_gui

Parameters:

strdata -- the colour string data to validate

Returns:

A boolean on whether any valid parser could be found for the string data

Return type:

bool

pygame_gui.core.colour_parser.is_valid_gradient_string(strdata: str) bool

Validate a gradient string A gradient string should consist of a 3 or 4 length comma separated list, with the first values being any valid colour strings and the last value representing a degree angle for the direction of the gradient. Examples: - "red,blue,40deg" - "#f23,rgb(30, 70, 230),hsv(50, 70%, 90%),50"

Parameters:

strdata (str) -- the gradient string to validate

Returns:

A boolean indicating whether the gradient string is valid or not

Return type:

bool

pygame_gui.core.colour_parser.is_valid_hex_string(strdata: str) bool
Validate Hex Color string in the format "#FFF", "#FFFF", "#FFFFFF", or "#FFFFFFFF"
Value Parameter Descriptions:

F: any hexadecimal digit between 0 and F inclusive

Examples:
  • "#A3F" (Shorthand)

  • "#98C4" (Shorthand with Alpha)

  • "#F3FAFF" (Full)

  • "#BD24A017" (Full, with Alpha)

Parameters:

strdata (str) -- the hex string to validate

Returns:

A boolean determining whether the string fits the determined hex schema

Return type:

bool

pygame_gui.core.colour_parser.is_valid_hsl_string(strdata: str) bool
Validate HSL Color string in the format "hsl(degree, percentage, percentage)"
Value Parameter Descriptions:
  • percentage: either an integer value from 0 to 100 with "%" appended at the end or a float value ranging from 0 to 1

  • degree: a value between 0 and 360 with the "deg" unit optionally appended to the end

Examples:
  • "hsl(30, 0.6, 0.7)"

  • "hsl(30deg, 40%, .5)"

Parameters:

strdata (str) -- the hsl string to validate

Returns:

A boolean determining whether the string fits the determined hsl schema

Return type:

bool

pygame_gui.core.colour_parser.is_valid_hsla_string(strdata: str) bool
Validate HSLA Color string in the format "hsla(degree, percentage, percentage, percentage)"
Value Parameter Descriptions:
  • percentage: either an integer value from 0 to 100 with "%" appended at the end or a float value ranging from 0 to 1

  • degree: a value between 0 and 360 with the "deg" unit optionally appended to the end

Examples:
  • "hsla(30, 0.6, 0.7, 80%)"

  • "hsla(30deg, 40%, .5, 40%)"

Parameters:

strdata (str) -- the hsla string to validate

Returns:

A boolean determining whether the string fits the determined hsla schema

Return type:

bool

pygame_gui.core.colour_parser.is_valid_hsv_string(strdata: str) bool
Validate HSLA Color string in the format "hsv(degree, percentage, percentage)"
Value Parameter Descriptions:
  • percentage: either an integer value from 0 to 100 with "%" appended at the end or a float value ranging from 0 to 1

  • degree: a value between 0 and 360 with the "deg" unit optionally appended to the end

Examples:
  • "hsv(50, 30%, .4)"

  • "hsv(60deg, 40%, 12%)"

Parameters:

strdata (str) -- the hsv string to validate

Returns:

A boolean determining whether the string fits the determined hsv schema

Return type:

bool

pygame_gui.core.colour_parser.is_valid_hsva_string(strdata: str) bool
Validate HSVA Color string in the format "hsva(degree, percentage, percentage, percentage)"
Value Parameter Descriptions:
  • percentage: either an integer value from 0 to 100 with "%" appended at the end or a float value ranging from 0 to 1

  • degree: a value between 0 and 360 with the "deg" unit optionally appended to the end

Examples:
  • "hsva(50, .3, 40%, .75)"

  • "hsva(60deg, 40%, 12%, .94)"

Parameters:

strdata (str) -- the hsva string to validate

Returns:

A boolean determining whether the string fits the determined hsva schema or not

Return type:

bool

pygame_gui.core.colour_parser.is_valid_rgb_string(strdata: str)
Validate RGB Color string in the format "rgb(uint8, uint8, uint8)"
Value Parameter Descriptions:
  • uint8: is an integer value bounded between 0 and 255

Examples:
  • "rgb(20, 40, 80)"

Parameters:

strdata (str) -- the rgb string to validate

Returns:

A boolean determining whether the string fits the determined rgb schema

Return type:

bool

pygame_gui.core.colour_parser.is_valid_rgba_string(strdata: str) bool
Validate RGBA Color string in the format "rgba(uint8, uint8, uint8, uint8)"
Value Parameter Descriptions:
  • uint8: is an integer value bounded between 0 and 255

Examples:
  • "rgba(30, 241, 174, 232)"

Parameters:

strdata (str) -- the rgba string to validate

Returns:

A boolean determining whether the string fits the determined rgba schema

Return type:

bool

pygame_gui.core.colour_parser.may_be_gradient_string(strdata: str) bool
Determine if a string should even be considered for validation as a gradient
Developer Notes:
  • Determines this by determining if there are 2 or 3 commas outside any enclosing glyph and if the enclosing glyphs in the colour string are validly closed and opened.

Parameters:

strdata (str) -- the possible gradient string to check

Returns:

If the gradient string passes the starting check

Return type:

bool

pygame_gui.core.colour_parser.parse_cmy_string(strdata: str) Color
Parse CMY Color string in the format "cmy(percentage, percentage, percentage)"
Value Parameter Descriptions:
  • percentage: either an integer value from 0 to 100 with "%" appended at the end or a float value ranging from 0 to 1

Examples:
  • "cmy(.4, .7, 80%)"

Parameters:

strdata (str) -- the cmy string to parse

Returns:

A pygame Color from the cmy data parsed from strdata

Return type:

pygame.Color

pygame_gui.core.colour_parser.parse_colour_model(strdata: str, name: str, types: List[NumParserType]) List[T]
Use a colour model's name and types (generally denoted by its name in the _colourModelSchemas dictionary) to return a tuple of its containing values
Developer Notes:
  • This function depends on the parser of each value type being present in the _valueParsers dictionary

  • This function assumes that the strdata parameter has already been validated against the validate_colour_model function

  • This function assumes that the colour model also takes up the form "name(value, value...)"

Parameters:
  • strdata (str) -- the colour model string to parse

  • name (str) -- the name of the colour model

  • types (List[NumParserType]) -- the types of the values in the colour model in order, used to parse each value individually

Returns:

A tuple containing all the parsed values in the colour model

Return type:

tuple

Raises:
  • ValueError -- if the colour model does not meet the standard <name(value, ...)> schema

  • KeyError -- if the colour model cannot find the parser for a given type or the given type is not defined to have a parser

pygame_gui.core.colour_parser.parse_colour_name(strdata: str) Color
Parse Colour name string into its corresponding colour value
As of the writing of these documentations, all colour names defined are from the CSS colours given by all major browsers, which can be found here: https://w3schools.sinsixx.com/css/css_colornames.asp.htm
All colour names are not case-sensitive, so RED, Red, and red all represent the same value
Parameters:

strdata (str) -- The colour name to parse

Returns:

A pygame Color from the colour name given by strdata

Return type:

pygame.Color

Raises:

KeyError -- If the colour corresponding to the strdata passed in could not be found ( always call is_valid_colour_name first to check )

pygame_gui.core.colour_parser.parse_colour_or_gradient_string(strdata: str) Color | ColourGradient | None
Parse a colour or gradient string into a pygame Color or a pygame_gui.core.colour_gradient.ColourGradient Object

The documentation for what counts as a 'Valid' colour and gradient string, including the supported colour formats by pygame_gui, can be found in the Theme Guide of the pygame_gui documentation at https://pygame-gui.readthedocs.io/en/v_065/theme_guide.html
Parameters:

strdata (str) -- the string data to parse into a colour or gradient

Returns:

The colour or gradient generated from the string data, or none

Return type:

pygame.Color, pygame_gui.core.colour_gradient.ColourGradient, or None

pygame_gui.core.colour_parser.parse_colour_string(strdata: str) Color | None
Parse a Color String
Developer Notes:
  • This function uses the implemented colour parsing and colour validating functions available through _colourParsers in order to determine a proper colour data

  • Additionally, named colour strings are taken into account firstly when determining the data of the colour

  • Note that this function returns the first valid occurrence that they find

Parameters:

strdata (str) -- The string to parse into a Colour

Returns:

A Pygame Color Object from the colour data parsed from strdata or None if the strdata is an invalid colour string

Return type:

pygame.Color or None

pygame_gui.core.colour_parser.parse_gradient_string(strdata: str) ColourGradient | None

Parse a gradient string A gradient string should consist of a 3 or 4 length comma separated list, with the first values being any valid colour strings and the last value representing a degree angle for the direction of the gradient Examples: - "red,blue,40deg" - "#f23,rgb(30, 70, 230),hsv(50, 70%, 90%),50"

Parameters:

strdata (str) -- the gradient string to validate

Returns:

A pygame_gui.core.colour_gradient.ColourGradient object if strdata is a valid gradient string, otherwise None

Return type:

bool or None

pygame_gui.core.colour_parser.parse_hex_string(strdata: str) Color
Parse Hex Color string in the formats "#FFF", "#FFFF", "#FFFFFF", or "#FFFFFFFF"
Value Parameter Descriptions:
  • F: any hexadecimal digit between 0 and F inclusive

Examples:
  • "#A3F" (Shorthand)

  • "#98C4" (Shorthand with Alpha)

  • "#F3FAFF" (Full)

  • "#BD24A017" (Full, with Alpha)

Parameters:

strdata (str) -- the hex string to parse

Returns:

A pygame Color from the hex data parsed from strdata

Return type:

pygame.Color

pygame_gui.core.colour_parser.parse_hsl_string(strdata: str) Color
Parse HSL Color string in the format "hsl(degree, percentage, percentage)"
Value Parameter Descriptions:
  • percentage: either an integer value from 0 to 100 with "%" appended at the end or a float value ranging from 0 to 1

  • degree: a value between 0 and 360 with the "deg" unit optionally appended to the end

Examples:
  • "hsl(30, 0.6, 0.7)"

  • "hsl(30deg, 40%, .5)"

Parameters:

strdata (str) -- the hsl string to parse

Returns:

A pygame Color from the hsl data parsed from strdata

Return type:

pygame.Color

pygame_gui.core.colour_parser.parse_hsla_string(strdata: str) Color
Parse HSLA Color string in the format "hsla(degree, percentage, percentage, percentage)"
Value Parameter Descriptions:
  • percentage: either an integer value from 0 to 100 with "%" appended at the end or a float value ranging from 0 to 1

  • degree: a value between 0 and 360 with the "deg" unit optionally appended to the end

Examples:
  • "hsla(30, 0.6, 0.7, 80%)"

  • "hsla(30deg, 40%, .5, 40%)"

Parameters:

strdata (str) -- the hsla string to parse

Returns:

A pygame Color from the hsla data parsed from strdata

Return type:

pygame.Color

pygame_gui.core.colour_parser.parse_hsv_string(strdata: str) Color
Parse HSV Color string in the format "hsv(degree, percentage, percentage)"
Value Parameter Descriptions:
  • percentage: either an integer value from 0 to 100 with "%" appended at the end or a float value ranging from 0 to 1

  • degree: a value between 0 and 360 with the "deg" unit optionally appended to the end

Examples:
  • "hsv(50, 30%, .4)"

  • "hsv(60deg, 40%, 12%)"

Parameters:

strdata (str) -- the hsv string to parse

Returns:

A pygame Color from the hsv data parsed from strdata

Return type:

pygame.Color

pygame_gui.core.colour_parser.parse_hsva_string(strdata: str) Color
Parse HSVA Color string in the format "hsva(degree, percentage, percentage, percentage)"
Value Parameter Descriptions:
  • percentage: either an integer value from 0 to 100 with "%" appended at the end or a float value ranging from 0 to 1

  • degree: a value between 0 and 360 with the "deg" unit optionally appended to the end

Examples:
  • "hsva(50, .3, 40%, .75)"

  • "hsva(60deg, 40%, 12%, .94)"

Parameters:

strdata (str) -- the hsva string to parse

Returns:

A pygame Color from the hsva data parsed from strdata

Return type:

pygame.Color

pygame_gui.core.colour_parser.parse_rgb_string(strdata: str) Color
Parse RGB Color string in the format "rgb(uint8, uint8, uint8)"
Value Parameter Descriptions:
  • uint8: is an integer value bounded between 0 and 255

Examples:
  • "rgb(20, 40, 80)"

Parameters:

strdata (str) -- the rgb string to parse

Returns:

A pygame Color from the data parsed from strdata

Return type:

pygame.Color

pygame_gui.core.colour_parser.parse_rgba_string(strdata: str) Color
Parse RGBA Color string in the format "rgba(uint8, uint8, uint8, uint8)"
Value Parameter Descriptions:
  • uint8: is an integer value bounded between 0 and 255

Examples:
  • "rgba(30, 241, 174, 232)"

Parameters:

strdata (str) -- the rgba string to parse

Returns:

A pygame Color from the rgba data parsed from strdata

Return type:

pygame.Color

pygame_gui.core.colour_parser.split_string_at_indices(strdata: str, indices: List[int] | Set[int] | Tuple[int]) List[str]
Works similarly to the built-in string split function, where the split data is discarded from the resultant array
Developer Notes:
  • Used in colour_parser module to split gradient strings into their respective colour and angle components

Parameters:
  • strdata (str) -- the string to split

  • indices (Iterable[int]) -- the indices to split the string at

Returns:

A list of the split strings after cutting at the specified indices given by the 'indices' parameter

Return type:

List[str]

pygame_gui.core.colour_parser.valid_enclosing_glyphs(strdata: str) bool
Find if each opening parenthesis in a string has a valid closing parenthesis and vice versa
Developer Notes:
  • Used to determine which top level commas should be used to separate gradients

  • Used with the assumption that colour values themselves do not have glyphs that are left opened

Parameters:

strdata (str) -- the string to check

Returns:

A boolean determining whether each opening parenthesis has a closing parenthesis and each closing parenthesis has an open parenthesis

Return type:

bool

pygame_gui.core.colour_parser.validate_colour_model(strdata: str, name: str, types: List[NumParserType]) bool
Use a colour model's name and types (generally denoted by its name in the _colourModelSchemas dictionary) to validate its use
Developer Notes:
  • This function depends on the validator of each value type being present in the _valueParsers dictionary

  • This function assumes that the colour model also takes up the form "name(value, value...)"

Parameters:
  • strdata (str) -- the colour model string to validate

  • name (str) -- the name of the colour model

  • types (List[NumParserType]) -- the types of the values in the colour model in order, used to validate each value individually

Returns:

A boolean on whether the colour model could find a working validator

Return type:

bool

pygame_gui.core.gui_font_pygame module

class pygame_gui.core.gui_font_pygame.GUIFontPygame(file: str | bytes | PathLike | IO | None, size: int | float, force_style: bool = False, style: Dict[str, bool] | None = None)

Bases: IGUIFontInterface

get_direction() int
Returns:

get_metrics(text: str)
Parameters:

text --

Returns:

get_padding_height()
Returns:

get_point_size()
get_rect(text: str) Rect

Not sure if we want this. :return:

render_premul(text: str, text_color: Color) Surface

Draws text to a surface ready for pre-multiplied alpha-blending

render_premul_to(text: str, text_colour: Color, surf_size: Tuple[int, int], surf_position: Tuple[int, int]) Surface
Parameters:
  • text --

  • text_colour --

  • surf_size --

  • surf_position --

Returns:

size(text: str) Tuple[int, int]

Return the pixel size of a given text string in this font

Parameters:

text -- the text to check.

Returns:

the width & height in pixels.

property underline: bool
Returns:

property underline_adjustment: float
Returns:

pygame_gui.core.layered_gui_group module

class pygame_gui.core.layered_gui_group.GUISprite(*groups)

Bases: object

A sprite class specifically designed for the GUI. Very similar to pygame's DirtySprite but without the Dirty flag.

add(*groups)

add the sprite to groups

Parameters:

groups -- sprite groups to add to.

Any number of Group instances can be passed as arguments. The Sprite will be added to the Groups it is not already a member of.

add_internal(group)

For adding this sprite to a group internally.

Parameters:

group -- The group we are adding to.

alive()

does the sprite belong to any groups

Sprite.alive(): return bool

Returns True when the Sprite belongs to one or more Groups.

property blendmode

Layer property can only be set before the sprite is added to a group, after that it is read only and a sprite's layer in a group should be set via the group's change_layer() method.

Overwrites dynamic property from sprite class for speed.

groups()

list of Groups that contain this Sprite

Sprite.groups(): return group_list

Returns a list of all the Groups that contain this Sprite.

property image

Layer property can only be set before the sprite is added to a group, after that it is read only and a sprite's layer in a group should be set via the group's change_layer() method.

Overwrites dynamic property from sprite class for speed.

kill()

remove the Sprite from all Groups

Sprite.kill(): return None

The Sprite is removed from all the Groups that contain it. This won't change anything about the state of the Sprite. It is possible to continue to use the Sprite after this method has been called, including adding it to Groups.

property layer

Layer property can only be set before the sprite is added to a group, after that it is read only and a sprite's layer in a group should be set via the group's change_layer() method.

Overwrites dynamic property from sprite class for speed.

property rect

Layer property can only be set before the sprite is added to a group, after that it is read only and a sprite's layer in a group should be set via the group's change_layer() method.

Overwrites dynamic property from sprite class for speed.

remove(*groups)

remove the sprite from groups

Parameters:

groups -- sprite groups to remove from.

Any number of Group instances can be passed as arguments. The Sprite will be removed from the Groups it is currently a member of.

remove_internal(group)

For removing this sprite from a group internally.

Parameters:

group -- The group we are removing from.

abstract update(time_delta: float)

A stub to override.

Parameters:

time_delta -- the time passed in seconds between calls to this function.

property visible

You can make this sprite disappear without removing it from the group assign 0 for invisible and 1 for visible

class pygame_gui.core.layered_gui_group.LayeredGUIGroup(*sprites)

Bases: LayeredUpdates

A sprite group specifically for the GUI. Similar to pygame's LayeredDirty group but with the dirty flag stuff removed for simplicity and speed. TODO: sever this entirely from LayeredUpdates at some point to fix the type hinting

add_internal(sprite: GUISprite, layer=None)

Do not use this method directly.

It is used by the group to add a sprite internally.

change_layer(sprite: GUISprite, new_layer)

change the layer of the sprite

LayeredUpdates.change_layer(sprite, new_layer): return None

The sprite must have been added to the renderer already. This is not checked.

draw(surface)

draw all sprites in the right order onto the given surface

remove_internal(sprite)

Do not use this method directly.

The group uses it to add a sprite.

update(*args, **kwargs) None
Parameters:
  • args --

  • kwargs --

update_visibility()

Update the list of what is currently visible.

Called when we add or remove elements from the group or when an element is hidden or shown.

pygame_gui.core.object_id module

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

Bases: tuple

class_id

Alias for field number 1

object_id

Alias for field number 0

pygame_gui.core.resource_loaders module

class pygame_gui.core.resource_loaders.BlockingThreadedResourceLoader

Bases: ThreadedLoader, 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.resource_loaders.IResourceLoader

Bases: object

Interface for a resource loader class. Resource loaders should inherit this interface.

abstract add_resource(resource: FontResource | ImageResource | SurfaceResource)

Adds a resource to be loaded.

Parameters:

resource -- Either an ImageResource, SurfaceResource or a FontResource.

abstract start()

Kicks off the loading process. No more resources can be added to the loader at this point.

abstract started() bool

Tells us if the loader has already begun or finished loading.

Returns:

Returns True when it's too late to add anything to the load queues.

abstract update() Tuple[bool, float]

Updates the load process.

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.resource_loaders.IncrementalThreadedResourceLoader

Bases: ThreadedLoader, 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.resource_loaders.ThreadedLoader

Bases: object

A loader that uses threads to try and load data faster.

Defaults to using five threads. Mess with it before starting the loader if you want to see if you can get any better loading performance with a different number.

add_resource(resource: FontResource | ImageResource | SurfaceResource)

Adds a resource to be loaded.

Currently Fonts & Images are loaded with threads. Surfaces load sequentially after the images are finished because they rely on their image being loaded and it is difficult to guarantee that with threads.

Parameters:

resource -- Either an ImageResource, SurfaceResource or a FontResource.

set_finished()

Called when loading is done.

start()

Kicks off the loading process. No more resources can be added to the loader at this point.

started() bool

Tells us if the loader has already begun or finished loading.

Returns:

Returns True when it's too late to add anything to the load queues.

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: 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[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: Color, bg_colour: Color, corner_radius: List[int] | None = 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) Surface | None

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: Rect, dividing_rect: Rect, free_space_rectangles: List[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 splitting.

  • 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: IResourceLoader, locale: str)

Bases: 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_base_ids: None | List[str | None], element_ids: None | List[str], class_ids: None | List[str | None], object_ids: None | List[str | None]) List[str]

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

Parameters:
  • element_base_ids -- when an element is also another element (e.g. a file dialog is also a window)

  • 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 = None) 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 = None) Color | 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]) IGUIFontInterface

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 an interleaved hierarchy of elements.

Return IGUIFontInterface:

An interface to a pygame font object wrapper.

get_font_dictionary() 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 an interleaved hierarchy of elements.

Return dictionary:

Data about the font requested

get_image(image_id: str, combined_element_ids: List[str]) 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]) str | Dict

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: str | PathLike | StringIO | PackageResource | dict)

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

Parameters:

file_path -- The location of the theme, or the theme data 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 | dict)

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

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

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

Parameters:
  • new_theming_data --

  • rebuild_all --

Returns:

pygame_gui.core.ui_container module

class pygame_gui.core.ui_container.UIContainer(relative_rect: Rect | FRect | Tuple[float, float, float, float], manager: IUIManagerInterface, *, starting_height: int = 1, is_window_root_container: bool = False, container: IContainerLikeInterface | None = None, parent_element: UIElement | None = None, object_id: ObjectID | str | None = None, element_id: List[str] | None = None, anchors: Dict[str, str] | None = None, visible: int = 1)

Bases: UIElement, IUIContainerInterface, IContainerLikeInterface

A UI Container holds any number of other UI elements inside 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, if any.

  • manager -- The UIManager that manages this UIElement.

  • starting_height -- The starting layer height for this element above its 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: 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.

are_contents_hovered() bool

Are any of the elements in the container hovered? Used for handling mousewheel events.

Returns:

True if one of the elements is hovered, False otherwise.

calc_add_element_changes_thickness(element: 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.

expand_left(width_increase: int) None

Increases the width of the container, but instead of expanding the right edge, it expands the left edge. This is achieved by setting the new dimensions and updating the anchors of all the elements anchored to the left of the container.

Parameters:

width_increase -- The width to increase by. Pass in negative values to decrease the size

Returns:

None

expand_top(height_increase: int) None

Increases the height of the container, but instead of expanding the bottom edge, it expands the top edge. This is achieved by setting the new dimensions and updating the anchors of all the elements anchored to the top of the container.

Parameters:

height_increase -- The height to increase by. Pass in negative values to decrease the size

Returns:

None

get_container() IUIContainerInterface

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

Returns:

This container.

get_rect() 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_contained_elements_changed(target: IUIElementInterface) None

Update the positioning of the contained elements of this container. To be called when one of the contained elements may have moved, been resized or changed its anchors.

Parameters:

target -- the UI element that has been benn moved resized or changed its anchors.

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: IUIElementInterface)

Remove a UIElement from this container.

Parameters:

element -- A UIElement to remove from this container.

set_dimensions(dimensions: Vector2 | Tuple[float, float], clamp_to_container: bool = False)

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

Parameters:
  • dimensions -- the new dimensions.

  • clamp_to_container -- Whether we should clamp the dimensions to the dimensions of the container or not.

set_position(position: Vector2 | 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: Vector2 | 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.

pygame_gui.core.ui_element module

class pygame_gui.core.ui_element.UIElement(relative_rect: Rect | FRect | Tuple[float, float, float, float], manager: IUIManagerInterface | None, container: IContainerLikeInterface | None, *, starting_height: int, layer_thickness: int, anchors: Dict[str, str | IUIElementInterface] | None = None, visible: int = 1, parent_element: IUIElementInterface | None = None, object_id: ObjectID | str | None = None, element_id: List[str] | None = None, ignore_shadow_for_initial_size_and_pos: bool = False)

Bases: GUISprite, 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 its 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.

  • parent_element -- Element that this element 'belongs to' in theming. Elements inherit colours from parents.

  • object_id -- An optional set of IDs to help distinguish this element from other elements.

  • element_id -- A list of string ID representing this element's class.

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.

change_object_id(new_object_id: ObjectID | str | None)

Allows for easy switching of an element's ObjectID used for theming and events.

Will rebuild the element after switching the ID

Parameters:

new_object_id -- The new ID to use for this element.

Returns:

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() 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_anchors() Dict[str, str | IUIElementInterface]

A dictionary containing all the anchors defining what the relative rect is relative to

Returns:

A dictionary containing all the anchors defining what the relative rect is relative to

get_class_ids() List[str]

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

Returns:

a list of strings, one for each element in the hierarchy.

get_element_base_ids() List[str]

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

Returns:

a list of strings, one for each element in the hierarchy.

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 for each element in the hierarchy.

get_focus_set() Set[IUIElementInterface]

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

get_image_clipping_rect() Rect | None

Obtain the current image clipping rect.

Returns:

The current clipping rect. Maybe None.

get_object_ids() List[str]

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

Returns:

a list of strings, one for each element in the hierarchy.

get_relative_rect() 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 its 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.

property hovered: bool

Are we hovering over this element with the mouse pointer or other input highlighting method.

Returns:

True if hovered.

join_focus_sets(element: IUIElementInterface)

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

Parameters:

element -- The other element whose focus set we are joining with.

kill()

Overriding regular sprite kill() method to remove the element from its 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()

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

Called when this UI element leaves the 'hovered' state.

process_event(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_anchors(anchors: Dict[str, str | IUIElementInterface] | None) None

Wraps the setting of the anchors with some validation

Parameters:

anchors -- A dictionary of anchors defining what the relative rect is relative to

Returns:

None

set_container(container: None | IContainerLikeInterface)

Switch the element to new container. Remove the element from the old container and add it to the new container.

Parameters:

container -- The new container to add.

set_dimensions(dimensions: Vector2 | Tuple[float, float], clamp_to_container: bool = False)

Method to directly set the dimensions of an element. And set whether the elements are dynamic.

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. If it is a negative value, the element will become dynamically sized, otherwise it will become statically sized.

  • clamp_to_container -- Whether we should clamp the dimensions to the dimensions of the container or not.

set_focus_set(focus_set: Set[IUIElementInterface] | None)

Set the focus set to a specific set of elements.

Parameters:

focus_set -- The focus set to set.

set_image(new_image: Surface | None)

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_minimum_dimensions(dimensions: Vector2 | 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: Vector2 | 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: Vector2 | 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 its 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: Vector2 | Tuple[int, int] | Tuple[float, float])

Called while we are in the hover state. It will create a tool tip if we've been in the hover state for a while, the text exists to create one, and we haven't created one already.

Parameters:
  • time_delta -- Time in seconds between calls to update.

  • mouse_pos -- The current position of the mouse.

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, script: str = 'Latn', direction: int = 0)

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: IResourceLoader, locale: str)

Bases: 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: str | PackageResource, bold_path: str | PackageResource | None = None, italic_path: str | PackageResource | None = None, bold_italic_path: str | 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 an 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.

create_font_id(font_size: int, font_name: str, bold: bool, italic: bool, antialiased: bool = True) 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.

  • antialiased -- Whether the font is antialiased 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, antialiased: bool = True, script: str = 'Latn', direction: int = 0) IGUIFontInterface

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.

  • antialiased -- Whether the font is antialiased or not.

  • script -- The ISO 15924 script code used for text shaping as a string.

  • direction -- the direction of text e.g. left to right or right to left. An integer.

Return IGUIFontInterface:

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, antialiased: bool = True, script: str = 'Latn', direction: int = 0) 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.

  • antialiased -- Whether the font is antialiased or not.

  • script -- The ISO 15924 script code used for text shaping as a string.

  • direction -- the direction of text e.g. left to right or right to left. An integer.

Return FontResource:

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

get_default_font() IGUIFontInterface

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, antialiased: bool = True, script: str = 'Latn', direction: int = 0)

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 preload 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.

  • antialiased -- Whether the font is antialiased or not.

  • script -- The ISO 15924 script code used for text shaping as a string.

  • direction -- the direction of text e.g. left to right or right to left. An integer.

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) 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_radii: List[int]) Surface | None

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_radii -- The radius of the rectangular shadow's corners.

create_shadow_corners(shadow_width_param: int, corner_radii: List[int], aa_amount=4) Dict[str, 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_radii -- Corner radii of the shadow.

  • aa_amount -- Antialiasing amount. Defaults to 4x.

find_closest_shadow_scale_to_size(size: Tuple[int, int], shadow_width: int = 2, shape: str = 'rectangle', corner_radius: List[int] | None = None) Surface | None

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: IUIContainerInterface)

Bases: 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: IWindowInterface)

Adds a new window to the top of the stack.

Parameters:

window -- The window to add.

clear()

Empties the whole stack removing and killing all windows.

get_full_stack() List[IWindowInterface]

Returns the full stack of normal and always on top windows.

Returns:

a list of Windows

is_window_at_top(window: IWindowInterface) bool

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

Parameters:

window -- The window to check.

Returns:

returns True if this window is at the top of the stack.

is_window_at_top_of_top(window: IWindowInterface) bool

Checks if a window is at the top of the top 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: IWindowInterface)

Moves the passed in window to the top of its 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: IWindowInterface)

Removes a window from the stack and resorts the remaining windows to adjust for its absence.

Parameters:

window_to_remove -- the window to remove.

Module contents

class pygame_gui.core.BlockingThreadedResourceLoader

Bases: ThreadedLoader, 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.ColourGradient(angle_direction: int, colour_1: Color, colour_2: Color, colour_3: Color | None = None)

Bases: 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: Surface, rect: Rect | None = 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.IContainerLikeInterface

Bases: object

A metaclass 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.

are_contents_hovered() bool

Are any of the elements in the container hovered? Used for handling mousewheel events.

Returns:

True if one of the elements is hovered, False otherwise.

abstract get_container() IUIContainerInterface

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

abstract 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.

abstract 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 metaclass 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.

abstract property always_on_top: bool

Whether the window is always above normal windows or not. :return:

abstract can_hover() bool

Called to test if this window can be hovered.

abstract change_layer(layer: int)

Change the drawing layer of this window.

Parameters:

layer -- the new layer to move to.

abstract check_clicked_inside_or_blocking(event: Event) bool

A quick event check outside 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.

abstract 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?

abstract 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_layer_thickness() int

The layer 'thickness' of this window/ :return: an integer

abstract 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).

abstract 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.

abstract property layer: int

The layer of this window (read-only)

abstract on_moved_to_front()

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

abstract process_event(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.

abstract rebuild()

Rebuilds the window when the theme has changed.

abstract 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.

abstract 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.

abstract set_dimensions(dimensions: Vector2 | 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.

abstract set_display_title(new_title: str)

Set the title of the window.

Parameters:

new_title -- The title to set.

abstract set_minimum_dimensions(dimensions: Vector2 | 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.

abstract set_position(position: Vector2 | Tuple[float, float])

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

Parameters:

position -- The new position to set.

abstract set_relative_position(position: Vector2 | Tuple[float, float])

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

Parameters:

position -- The new position to set.

abstract 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.

abstract 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.IncrementalThreadedResourceLoader

Bases: ThreadedLoader, 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.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.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) 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_radii: List[int]) Surface | None

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_radii -- The radius of the rectangular shadow's corners.

create_shadow_corners(shadow_width_param: int, corner_radii: List[int], aa_amount=4) Dict[str, 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_radii -- Corner radii of the shadow.

  • aa_amount -- Antialiasing amount. Defaults to 4x.

find_closest_shadow_scale_to_size(size: Tuple[int, int], shadow_width: int = 2, shape: str = 'rectangle', corner_radius: List[int] | None = None) Surface | None

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.TextBoxLayout(input_data_queue: Deque[TextLayoutRect], layout_rect: Rect, view_rect: Rect, line_spacing: float, default_font_data: Dict[str, Any], allow_split_dashes: bool = True, text_direction: int = 0, text_x_scroll_enabled: bool = False, editable: bool = False)

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[TextLayoutRect])

Pass in a list of layout rectangles to add to a hover-able 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 LayoutRects 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: 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: 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() 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[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 not 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: HTMLParser | None)

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: HTMLParser | None = 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: 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_cursor_to_end_of_current_row()

Set the edit cursor position in the text layout to the end of the current row and returns the overall position in the text

Returns:

the overall position of the cursor in the text layout, after setting it to the end of the current row

set_cursor_to_start_of_current_row()

Set the edit cursor position in the text layout to the end of the current row and returns the overall position in the text

Returns:

the overall position of the cursor in the text layout, after setting it to the end of the current row

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.

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

Bases: 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_base_ids: None | List[str | None], element_ids: None | List[str], class_ids: None | List[str | None], object_ids: None | List[str | None]) List[str]

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

Parameters:
  • element_base_ids -- when an element is also another element (e.g. a file dialog is also a window)

  • 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 = None) 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 = None) Color | 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]) IGUIFontInterface

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 an interleaved hierarchy of elements.

Return IGUIFontInterface:

An interface to a pygame font object wrapper.

get_font_dictionary() 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 an interleaved hierarchy of elements.

Return dictionary:

Data about the font requested

get_image(image_id: str, combined_element_ids: List[str]) 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]) str | Dict

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: str | PathLike | StringIO | PackageResource | dict)

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

Parameters:

file_path -- The location of the theme, or the theme data 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 | dict)

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

update_theming(new_theming_data: str | dict, 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: Rect | FRect | Tuple[float, float, float, float], manager: IUIManagerInterface, *, starting_height: int = 1, is_window_root_container: bool = False, container: IContainerLikeInterface | None = None, parent_element: UIElement | None = None, object_id: ObjectID | str | None = None, element_id: List[str] | None = None, anchors: Dict[str, str] | None = None, visible: int = 1)

Bases: UIElement, IUIContainerInterface, IContainerLikeInterface

A UI Container holds any number of other UI elements inside 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, if any.

  • manager -- The UIManager that manages this UIElement.

  • starting_height -- The starting layer height for this element above its 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: 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.

are_contents_hovered() bool

Are any of the elements in the container hovered? Used for handling mousewheel events.

Returns:

True if one of the elements is hovered, False otherwise.

calc_add_element_changes_thickness(element: 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.

expand_left(width_increase: int) None

Increases the width of the container, but instead of expanding the right edge, it expands the left edge. This is achieved by setting the new dimensions and updating the anchors of all the elements anchored to the left of the container.

Parameters:

width_increase -- The width to increase by. Pass in negative values to decrease the size

Returns:

None

expand_top(height_increase: int) None

Increases the height of the container, but instead of expanding the bottom edge, it expands the top edge. This is achieved by setting the new dimensions and updating the anchors of all the elements anchored to the top of the container.

Parameters:

height_increase -- The height to increase by. Pass in negative values to decrease the size

Returns:

None

get_container() IUIContainerInterface

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

Returns:

This container.

get_rect() 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_contained_elements_changed(target: IUIElementInterface) None

Update the positioning of the contained elements of this container. To be called when one of the contained elements may have moved, been resized or changed its anchors.

Parameters:

target -- the UI element that has been benn moved resized or changed its anchors.

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: IUIElementInterface)

Remove a UIElement from this container.

Parameters:

element -- A UIElement to remove from this container.

set_dimensions(dimensions: Vector2 | Tuple[float, float], clamp_to_container: bool = False)

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

Parameters:
  • dimensions -- the new dimensions.

  • clamp_to_container -- Whether we should clamp the dimensions to the dimensions of the container or not.

set_position(position: Vector2 | 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: Vector2 | 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: Rect | FRect | Tuple[float, float, float, float], manager: IUIManagerInterface | None, container: IContainerLikeInterface | None, *, starting_height: int, layer_thickness: int, anchors: Dict[str, str | IUIElementInterface] | None = None, visible: int = 1, parent_element: IUIElementInterface | None = None, object_id: ObjectID | str | None = None, element_id: List[str] | None = None, ignore_shadow_for_initial_size_and_pos: bool = False)

Bases: GUISprite, 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 its 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.

  • parent_element -- Element that this element 'belongs to' in theming. Elements inherit colours from parents.

  • object_id -- An optional set of IDs to help distinguish this element from other elements.

  • element_id -- A list of string ID representing this element's class.

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.

change_object_id(new_object_id: ObjectID | str | None)

Allows for easy switching of an element's ObjectID used for theming and events.

Will rebuild the element after switching the ID

Parameters:

new_object_id -- The new ID to use for this element.

Returns:

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() 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_anchors() Dict[str, str | IUIElementInterface]

A dictionary containing all the anchors defining what the relative rect is relative to

Returns:

A dictionary containing all the anchors defining what the relative rect is relative to

get_class_ids() List[str]

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

Returns:

a list of strings, one for each element in the hierarchy.

get_element_base_ids() List[str]

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

Returns:

a list of strings, one for each element in the hierarchy.

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 for each element in the hierarchy.

get_focus_set() Set[IUIElementInterface]

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

get_image_clipping_rect() Rect | None

Obtain the current image clipping rect.

Returns:

The current clipping rect. Maybe None.

get_object_ids() List[str]

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

Returns:

a list of strings, one for each element in the hierarchy.

get_relative_rect() 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 its 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.

property hovered: bool

Are we hovering over this element with the mouse pointer or other input highlighting method.

Returns:

True if hovered.

join_focus_sets(element: IUIElementInterface)

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

Parameters:

element -- The other element whose focus set we are joining with.

kill()

Overriding regular sprite kill() method to remove the element from its 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()

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

Called when this UI element leaves the 'hovered' state.

process_event(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_anchors(anchors: Dict[str, str | IUIElementInterface] | None) None

Wraps the setting of the anchors with some validation

Parameters:

anchors -- A dictionary of anchors defining what the relative rect is relative to

Returns:

None

set_container(container: None | IContainerLikeInterface)

Switch the element to new container. Remove the element from the old container and add it to the new container.

Parameters:

container -- The new container to add.

set_dimensions(dimensions: Vector2 | Tuple[float, float], clamp_to_container: bool = False)

Method to directly set the dimensions of an element. And set whether the elements are dynamic.

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. If it is a negative value, the element will become dynamically sized, otherwise it will become statically sized.

  • clamp_to_container -- Whether we should clamp the dimensions to the dimensions of the container or not.

set_focus_set(focus_set: Set[IUIElementInterface] | None)

Set the focus set to a specific set of elements.

Parameters:

focus_set -- The focus set to set.

set_image(new_image: Surface | None)

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_minimum_dimensions(dimensions: Vector2 | 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: Vector2 | 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: Vector2 | 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 its 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: Vector2 | Tuple[int, int] | Tuple[float, float])

Called while we are in the hover state. It will create a tool tip if we've been in the hover state for a while, the text exists to create one, and we haven't created one already.

Parameters:
  • time_delta -- Time in seconds between calls to update.

  • mouse_pos -- The current position of the mouse.

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

Bases: 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: str | PackageResource, bold_path: str | PackageResource | None = None, italic_path: str | PackageResource | None = None, bold_italic_path: str | 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 an 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.

create_font_id(font_size: int, font_name: str, bold: bool, italic: bool, antialiased: bool = True) 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.

  • antialiased -- Whether the font is antialiased 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, antialiased: bool = True, script: str = 'Latn', direction: int = 0) IGUIFontInterface

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.

  • antialiased -- Whether the font is antialiased or not.

  • script -- The ISO 15924 script code used for text shaping as a string.

  • direction -- the direction of text e.g. left to right or right to left. An integer.

Return IGUIFontInterface:

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, antialiased: bool = True, script: str = 'Latn', direction: int = 0) 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.

  • antialiased -- Whether the font is antialiased or not.

  • script -- The ISO 15924 script code used for text shaping as a string.

  • direction -- the direction of text e.g. left to right or right to left. An integer.

Return FontResource:

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

get_default_font() IGUIFontInterface

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, antialiased: bool = True, script: str = 'Latn', direction: int = 0)

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 preload 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.

  • antialiased -- Whether the font is antialiased or not.

  • script -- The ISO 15924 script code used for text shaping as a string.

  • direction -- the direction of text e.g. left to right or right to left. An integer.

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.UIWindowStack(window_resolution: Tuple[int, int], root_container: IUIContainerInterface)

Bases: 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: IWindowInterface)

Adds a new window to the top of the stack.

Parameters:

window -- The window to add.

clear()

Empties the whole stack removing and killing all windows.

get_full_stack() List[IWindowInterface]

Returns the full stack of normal and always on top windows.

Returns:

a list of Windows

is_window_at_top(window: IWindowInterface) bool

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

Parameters:

window -- The window to check.

Returns:

returns True if this window is at the top of the stack.

is_window_at_top_of_top(window: IWindowInterface) bool

Checks if a window is at the top of the top 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: IWindowInterface)

Moves the passed in window to the top of its 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: IWindowInterface)

Removes a window from the stack and resorts the remaining windows to adjust for its absence.

Parameters:

window_to_remove -- the window to remove.