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,ABCA 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 thanIconitself.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
Nonefor the provider’s default.
- Returns:
The now-active
IconSet.- Return type:
- 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 onIconitself, or with an expliciticon_set,namemust 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
nameis not in the set.- Raises:
RuntimeError – If no icon set is given, the class has no provider, and none is initialized.
- Return type:
- 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’sforegroundmap whenstatespecis omitted), generates a child style name, and maps theimageoption 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 wherespecis a color string or a dict withnameand/orcolor. Ifcoloris omitted, the icon color follows the parent’sforegroundfor that state.mode (Literal['replace', 'merge']) – Merge strategy for the child style’s
imagemap."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 image: PhotoImage#
The Tk-compatible image, rendered on first access.
- name#
- 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_pilwork 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.NoneonIconitself, which has no pack of its own.
- size#
- tkinter_icons.create_transparent_icon(size=16)#
Return a cached fully transparent square image of
sizepixels.
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:
objectKnobs 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.
Noneselects 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
overridesapplied, ignoringNonevalues.- Parameters:
**overrides – Any field of
RenderOptions. A value ofNoneleaves the existing value alone, so callers can pass optional arguments straight through.- Returns:
A new
RenderOptions;selfis unchanged.- Return type:
- 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 withgetbbox, 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
glyphis empty.- Return type:
- 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
refpixels.glyph (str) – The single character to measure.
ref (int) – The size
fontwas 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, orNoneif the glyph renders no pixels.- Return type:
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:
objectOne 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, orNoneif it is not in this set.
- ink(name)#
Return precomputed ink bounds for
name, orNoneto measure live.
- 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)
IconSetfor a provider and style.- Parameters:
provider (BaseFontProvider) – The provider to load assets from.
style (Optional[str]) – Style name, or
Nonefor the provider’s default.
- Returns:
The shared
IconSet. Repeat calls return the same object.- Return type:
Packs#
- class tkinter_icons.Pack(extra, distribution, module, icon_class, provider, label, alias='')#
Bases:
objectOne 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_metricstool.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 toicon_classwhere that was already the natural name.
- 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.
- 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.
- 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.
- 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.