API reference#

Everything an application needs is importable from tkinter_icons. The machinery for defining an icon set — providers and the registry — is a developer API and lives in Contributing.

Icons#

class tkinter_icons.Icon(name, size=24, color='black', *, options=None)#

Bases: StatefulIconMixin, ABC

A font glyph rendered to a Tk-compatible image.

Provider packages subclass this and resolve friendly names to glyph names before delegating here, so you normally construct BootstrapIcon, FontAwesomeIcon, and so on rather than Icon itself.

Rendering is lazy: the image is drawn on first access to image, so icons can be built before a Tk root exists. Identical icons share one image.

Variables:
  • name – The resolved glyph name within the icon set.

  • size – Requested pixel size. The rendered image may be one pixel larger when odd sizes are snapped even — see RenderOptions.snap_even.

  • color – Foreground color.

  • on_missing (ClassVar[Literal['transparent', 'warn', 'raise']]) – Class-level policy for names absent from the icon set.

classmethod cache_info()#

Return current cache sizes, for debugging and tests.

classmethod cleanup()#

Release every cached image, font, and icon set.

Not required for correctness — nothing is written to disk and caches are dropped with their interpreter — but useful to reclaim memory in a long-running process that has finished with icons.

classmethod clear_cache()#

Drop every rendered image, keeping loaded fonts and icon sets.

Call after changing something that affects how icons look — a theme change, for instance — to force a redraw on next use.

classmethod initialize_with_provider(provider, style=None)#

Make a provider’s style the active icon set.

Icon sets are cached, so switching back and forth between providers costs nothing after the first load and does not disturb icons already created — each icon holds its own set.

Parameters:
  • provider (BaseFontProvider) – The provider to load.

  • style (str | None) – Style name, or None for the provider’s default.

Returns:

The now-active IconSet.

Return type:

IconSet

classmethod render_pil(name, size=24, color='black', *, icon_set=None, options=None)#

Render a glyph to a PIL image without needing a Tk root.

The way in for anything that wants pixels rather than a widget image — exporting a PNG, compositing, or testing the renderer headlessly.

Called on a pack’s icon class this needs nothing set up first — the pack supplies its own provider, so MaterialIcon.render_pil("home") draws a Material icon in a fresh process and takes the same friendly names the constructor does. Called on Icon itself, or with an explicit icon_set, name must already be a glyph name.

Parameters:
  • name (str) – Icon name. Resolved through the pack’s provider when called on a pack class with no explicit icon_set; otherwise taken as an already-resolved glyph name.

  • size (int) – Pixel size.

  • color (str) – Foreground color.

  • icon_set (IconSet | None) – Which set to draw from. Defaults to the pack’s own, then to the active one.

  • options (RenderOptions | None) – Overrides of the set’s render options.

Returns:

A square RGBA image; fully transparent if name is not in the set.

Raises:

RuntimeError – If no icon set is given, the class has no provider, and none is initialized.

Return type:

Image

map(widget, *, subclass=None, statespec=None, mode='merge')#

Apply per-state images to a child style derived from the widget’s style.

This computes per-state images from statespec (or the parent’s foreground map when statespec is omitted), generates a child style name, and maps the image option accordingly. The empty-state ('') fallback is always set to the instance’s original untinted image.

Parameters:
  • widget (Widget) – ttk widget to style (e.g., ttk.Button).

  • subclass (str | None) – Optional child style prefix. If omitted, the name is generated by hashing the unique icon names used (including the base) and size, e.g., "a3f4e7b2c1d6.my.TButton".

  • statespec (list[tuple[str, str | dict[str, str]]] | None) – Optional list of per-state overrides. Each item is a (state, spec) pair where spec is a color string or a dict with name and/or color. If color is omitted, the icon color follows the parent’s foreground for that state.

  • mode (Literal['replace', 'merge']) – Merge strategy for the child style’s image map. "merge", the default, reads the existing map for the same child style, overwrites incoming states, preserves the order of existing entries, and appends new ones. "replace" ignores any existing map and applies only the states given, plus the fallback.

to_pil()#

Render this icon to a PIL image, bypassing Tk entirely.

unmap(widget)#

Stop tracking widget, so theme changes no longer restyle it.

Rarely needed — a destroyed widget forgets itself — but useful to release an icon early on a widget that outlives its icon.

Parameters:

widget (Widget) – A widget previously passed to map.

color#
property icon_set: IconSet#

The icon set this icon draws from.

property image: PhotoImage#

The Tk-compatible image, rendered on first access.

name#
on_missing: ClassVar[Literal['transparent', 'warn', 'raise']] = 'transparent'#
property options: RenderOptions#

The render options in effect for this icon.

provider_class: ClassVar[type[BaseFontProvider] | None] = None#

The provider a pack’s icon class draws from, set by that class. It is what lets render_pil work as a classmethod on a pack: without it, MaterialIcon.render_pil("home") depends on some other call having initialized a provider first, and raises in a fresh process. None on Icon itself, which has no pack of its own.

property rendered_size: int#

The image’s actual pixel size, after even-snapping.

size#
tkinter_icons.create_transparent_icon(size=16)#

Return a cached fully transparent square image of size pixels.

Pack icon classes#

Each pack exports one class, and each of them is a subclass of Icon adding nothing but name resolution. The constructor is the same everywhere:

PackIcon(name: str, size: int = 24, color: str = "black", style: str | None = None)

style is accepted only by packs that have styles; the rest take three arguments. Both spellings of every class are exported — MaterialIcon and MatIcon, FontAwesomeIcon and FAIcon, GoogleMaterialIcon and GMatIcon — so code written against either keeps working. Icon packs lists them.

Rendering#

class tkinter_icons.RenderOptions(pad_factor=0.1, y_bias=0.0, scale_to_fit=True, oversample=None, align=False, sharpen=True, snap_even=True)#

Bases: object

Knobs controlling how a glyph is drawn into its frame.

A provider supplies the defaults for its icon set; individual calls can override any of them via RenderOptions.merge.

Variables:
  • pad_factor (float) – Fraction of the frame reserved as padding on each edge. The glyph’s ink is fitted to the box that remains.

  • y_bias (float) – Extra vertical offset as a fraction of the frame, applied after centering. Rarely needed once ink metrics are available — it exists to nudge icon sets whose glyphs are intentionally off-center.

  • scale_to_fit (bool) – Shrink the glyph so its ink fits inside the padded box. When false the glyph is drawn at the frame size and only centered.

  • oversample (int | None) – Render at this multiple of the target size and downscale. None selects a factor from the target size (3x under 32px, 2x under 64px, 1x above).

  • align (bool) – Snap the draw origin to the pixel grid of the final image, so edges land on whole pixels instead of being antialiased across a sub-pixel offset. Crisper for standalone marks that fill their frame; off by default so glyphs sitting beside text keep their exact optical centering.

  • sharpen (bool) – Apply a light unsharp mask after downscaling, restoring the edge contrast that LANCZOS softens. No effect when not oversampling.

  • snap_even (bool) – Round the requested size up to an even number of pixels. Eliminates half-pixel blur at fractional display scale factors (125%, 150%), where an odd size lands the glyph between pixels.

merge(**overrides)#

Return a copy with overrides applied, ignoring None values.

Parameters:

**overrides – Any field of RenderOptions. A value of None leaves the existing value alone, so callers can pass optional arguments straight through.

Returns:

A new RenderOptions; self is unchanged.

Return type:

RenderOptions

align: bool = False#
oversample: int | None = None#
pad_factor: float = 0.1#
scale_to_fit: bool = True#
sharpen: bool = True#
snap_even: bool = True#
y_bias: float = 0.0#
tkinter_icons.render_glyph(glyph, size, color, *, font_key, font_bytes, ink=None, options=RenderOptions(pad_factor=0.1, y_bias=0.0, scale_to_fit=True, oversample=None, align=False, sharpen=True, snap_even=True))#

Draw a single glyph centered in a square RGBA image.

Parameters:
  • glyph (str) – The character to draw.

  • size (int) – Edge length of the output in pixels, before even-snapping.

  • color (str) – Fill color, in any form Pillow accepts.

  • font_key (str) – Stable identity for the font file (see load_font).

  • font_bytes (bytes) – The raw font file.

  • ink (Sequence[float] | None) – Precomputed normalized ink bounds for this glyph, from measure_ink_bounds. When omitted, the glyph is measured at render time with getbbox, which is less accurate for full-bleed glyphs.

  • options (RenderOptions) – How to fit, center, and post-process the glyph.

Returns:

A square RGBA image of the snapped size. Fully transparent if glyph is empty.

Return type:

Image

tkinter_icons.measure_ink_bounds(font, glyph, *, ref=512, precision=5)#

Measure a glyph’s true inked bounds as fractions of the font size.

A glyph’s ink is color-independent and scales linearly with font size, so this only has to run once per glyph — offline, at a high reference size — and the result is reusable at every render size.

Parameters:
  • font (FreeTypeFont) – A font already instantiated at ref pixels.

  • glyph (str) – The single character to measure.

  • ref (int) – The size font was created at.

  • precision (int) – Decimal places to keep in the returned fractions.

Returns:

[left, top, width, height] relative to the text draw origin, as fractions of the font size, or None if the glyph renders no pixels.

Return type:

list[float] | None

Icon sets#

class tkinter_icons.IconSet(id, font_bytes, glyphs, metrics=<factory>, options=RenderOptions(pad_factor=0.1, y_bias=0.0, scale_to_fit=True, oversample=None, align=False, sharpen=True, snap_even=True))#

Bases: object

One provider’s glyphs in one style, ready to render.

Variables:
  • id (str) – Stable identity, "<provider>:<style>". Used as the cache key and as part of every rendered-image cache key.

  • font_bytes (bytes) – The raw font file backing this style.

  • glyphs (Mapping[str, str]) – Icon name to the single character that draws it.

  • metrics (Mapping[str, Sequence[float]]) – Icon name to normalized ink bounds, from the provider’s metrics.json. Empty when the provider ships none, in which case the renderer measures at draw time.

  • options (RenderOptions) – The provider’s default render options for this style.

glyph(name)#

Return the character for name, or None if it is not in this set.

ink(name)#

Return precomputed ink bounds for name, or None to measure live.

font_bytes: bytes#
property font_key: str#

Cache key identifying this set’s font file.

glyphs: Mapping[str, str]#
id: str#
metrics: Mapping[str, Sequence[float]]#
options: RenderOptions = RenderOptions(pad_factor=0.1, y_bias=0.0, scale_to_fit=True, oversample=None, align=False, sharpen=True, snap_even=True)#
tkinter_icons.get_icon_set(provider, style=None)#

Build (or return the cached) IconSet for a provider and style.

Parameters:
  • provider (BaseFontProvider) – The provider to load assets from.

  • style (Optional[str]) – Style name, or None for the provider’s default.

Returns:

The shared IconSet. Repeat calls return the same object.

Return type:

IconSet

Packs#

class tkinter_icons.Pack(extra, distribution, module, icon_class, provider, label, alias='')#

Bases: object

One installable icon pack.

Variables:
  • extra (str) – The extra to install it with, as in tkinter-icons[extra].

  • distribution (str) – The underlying PyPI distribution name.

  • module (str) – The importable module it provides.

  • icon_class (str) – The icon class as named in module.

  • provider (str) – The provider name it registers under, used by the registry and the generate_metrics tool.

  • label (str) – Human-readable name of the upstream icon set.

  • alias (str) – The name this class is exported as from tkinter_icons. The packs grew inconsistent short names (MatIcon, FAIcon, GMatIcon), so the base package offers a spelled-out one that matches the extra. Equal to icon_class where that was already the natural name.

alias: str = ''#
distribution: str#
property export_names: tuple[str, ...]#

Every name this pack’s icon class is reachable by from the base.

Both spellings are exported so existing code that imported the short name keeps working after switching to the single import root.

extra: str#
icon_class: str#
property import_statement: str#

The recommended import line for this pack’s icon class.

Uses the single import root so the name installed is the name imported. from {self.module} import {self.icon_class} also works.

property install_command: str#

The pip command that installs this pack.

Quoted because most shells treat unquoted brackets as globs — zsh fails outright on pip install tkinter-icons[material].

property is_installed: bool#

Whether this pack’s module can be imported.

label: str#
module: str#
provider: str#
tkinter_icons.KNOWN_PACKS#

Built-in immutable sequence.

If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable’s items.

If the argument is a tuple, the return value is the same object.

tkinter_icons.find_pack(key)#

Look up a pack by any of the names it goes by.

Accepts the extra, the distribution, the module, or the provider name, so a user who knows the pack by any of those gets the same answer.

Parameters:

key (str) – Extra, distribution, module, or provider name.

Returns:

The matching Pack, or None.

Return type:

Pack | None

tkinter_icons.installed_packs()#

Return every known pack that is importable in this environment.

Packaging#

tkinter_icons.get_hook_dirs()#

Return the directory containing PyInstaller hooks for this package.