PyHMI API Reference

Complete documentation of all public classes, methods, properties, and events.

Version: 0.3.1 | License: Apache 2.0

Table of Contents

Core Engine

Engine

Module: pyhmi.core.engine

Central orchestrator for the PyHMI framework. Manages display backend, widget tree, event system, layout, binding, and animation subsystems.

from pyhmi import Engine, Sdl2Display

display = Sdl2Display(width=320, height=240)
engine = Engine(display, target_fps=30)

Constructor

ParameterTypeDescription
displayDisplayBackendDisplay backend instance
target_fpsintFrame rate cap (0 = use default 15)

Properties

PropertyTypeDescription
displayDisplayBackendActive display backend
event_systemEventSystemGlobal event system
binding_engineBindingEngineData binding engine
animation_engineAnimationEngineAnimation engine
treeWidgetTreeRoot widget tree
target_fpsintFrame rate cap (default 15)
touch_toleranceintTouch hit tolerance in pixels (proxies the tree, default 8)
themeAny | NoneActive theme (StyleTemplate or editor theme dict)
gesture_recognizerGestureRecognizerTouch gesture recognizer
painterPainterShared painter for the active display
inputInputBackend | NoneActive input backend

Methods

MethodSignatureDescription
set_root(widget: WidgetBase) -> NoneSet the root widget
set_layout(layout: Layout) -> NoneSet the layout engine
register_template(template: StyleTemplate) -> NoneRegister a style template
set_active_template(name: str) -> NoneActivate a theme template
add_frame_callback(callback: Callable[[float], None]) -> NoneAdd per-frame callback
mark_dirty() -> NoneRequest a re-render on the next loop iteration
run() -> NoneStart the main event loop
stop() -> NoneStop the event loop
resize(width: int, height: int) -> NoneHandle window resize

WidgetBase

Module: pyhmi.core.widget

Base class for all PyHMI widgets. Provides common properties, event handling, and rendering hooks.

from pyhmi import WidgetBase

class MyWidget(WidgetBase):
    def render(self, painter, x, y):
        painter.draw_rect(x, y, self.width, self.height, (50, 50, 50, 255))

Properties

PropertyTypeDefaultDescription
idstr | NoneNoneUnique identifier
xint0X position
yint0Y position
widthint0Width in pixels
heightint0Height in pixels
visibleboolTrueVisibility flag
enabledboolTrueInteraction enabled
checkedboolFalseChecked state (toggles)
focusedboolFalseKeyboard focus
textstr""Display text
background_colorTuple[int,int,int,int](0,0,0,0)RGBA background
text_colorTuple[int,int,int](255,255,255)RGB text color
font_sizeint12Font size in pixels
border_widthint0Border width
border_colorTuple[int,int,int](128,128,128)Border color
border_radiusint0Border corner radius
paddingint0Internal padding
marginint0External margin
opacityfloat1.0Opacity (0.0-1.0)
touch_toleranceint0Hit-test tolerance in pixels (0 = inherit tree default)
parentWidgetBase | NoneNoneRead-only parent
childrenList[WidgetBase][]Read-only children list
style_templatestr | NoneNoneApplied template name

Methods

MethodSignatureDescription
add_child(child: WidgetBase) -> NoneAdd child widget
remove_child(child: WidgetBase) -> NoneRemove child widget
on(event_type: EventType, handler: Callable) -> NoneRegister event handler
on_signal(signal_name: str, handler: Callable) -> NoneRegister named signal handler
on_event(event: Event) -> boolHandle incoming event (override)
emit(event: Event | str, data: dict) -> NoneEmit event or signal
render(surface: Any, x: int, y: int) -> NoneRender widget (override)
update(dt: float) -> NoneUpdate state (override)
render_recursive(surface, x, y) -> NoneRender self + children
hit_test(mx: int, my: int) -> WidgetBase | NonePoint hit detection
contains_point(mx: int, my: int) -> boolBounds check

Class Attributes

AttributeTypeDescription
registryDict[str, type]Auto-registered subclasses

WidgetTree

Module: pyhmi.core.tree

Hierarchical widget model with layout computation, coordinated rendering, and event dispatch.

MethodSignatureDescription
set_root(widget: WidgetBase) -> NoneSet root widget
set_layout(layout: Layout) -> NoneSet layout engine
compute_layout() -> NoneCompute positions for all widgets
render(surface: Any) -> NoneRender entire tree
update(dt: float) -> NoneUpdate all widgets
traverse() -> List[WidgetBase]Depth-first traversal
handle_click(x: int, y: int) -> NoneDispatch click event
handle_touch_press(x: int, y: int) -> NoneDispatch touch press
handle_touch_release(x: int, y: int) -> NoneDispatch touch release
handle_key_press(key: str, mod: int) -> NoneDispatch key press
handle_scroll(x: int, y: int, dx: int, dy: int) -> NoneDispatch mouse wheel to deepest scrollable widget
handle_resize(width: int, height: int) -> NoneDispatch resize

Occlusion culling: render_recursive skips siblings beneath any visible child with _occludes_siblings=True that fully covers its parent (pixel-identical, only faster).

Touch tolerance: touch_tolerance (default DEFAULT_TOUCH_TOLERANCE = 8) expands hit-test bounds; a widget's own value (> 0) wins, otherwise the tree value applies.

Event System

Module: pyhmi.core.event

EventType Enum

ValueDescription
CLICKMouse/touch click
TOUCH_PRESSTouch down
TOUCH_RELEASETouch up
TOUCH_DRAGTouch move
WHEELMouse wheel scroll (carries dx/dy in data)
KEY_PRESSKey press
VALUE_CHANGEDValue change
FOCUS_INFocus gained
FOCUS_OUTFocus lost
RESIZEWidget resized
CUSTOMCustom event

Event Class

PropertyTypeDescription
typeEventTypeEvent type
targetWidgetBaseOriginating widget
current_targetWidgetBaseCurrent propagation target
propagateboolContinue bubbling (default True)
datadictArbitrary event data

EventSystem Class

Global event dispatcher. Use engine.event_system to access.

Layout Engine

Module: pyhmi.core.layout

FlexLayout

Row or column layout with alignment, spacing, and wrap support.

from pyhmi import FlexLayout

layout = FlexLayout(
    direction="column",
    main_alignment="center",
    cross_alignment="start",
    spacing=10,
    wrap=False,
)
ParameterTypeDefaultDescription
directionstr"row""row" or "column"
main_alignmentstr"start""start", "center", "end", "space_between"
cross_alignmentstr"start""start", "center", "end", "stretch"
spacingint0Pixel spacing between children
wrapboolFalseAllow wrapping

GridLayout

Grid layout with rows, columns, span, and alignment.

from pyhmi import GridLayout

layout = GridLayout(
    columns=3,
    rows=2,
    spacing=5,
    alignment="center",
)
ParameterTypeDefaultDescription
columnsint1Number of columns
rowsint1Number of rows
spacingint0Pixel spacing
alignmentstr"start"Cell alignment

Data Binding

Module: pyhmi.core.binding

Observable

Observable property with subscribers and dependency tracking.

from pyhmi import Observable

temp = Observable(22, name="temperature")
temp.subscribe(lambda v: print(f"Temp: {v}"))
temp.value = 25  # Prints "Temp: 25"
MethodDescription
subscribe(callback)Subscribe to value changes
watch(callback)Watch with old/new values
valueGet/set current value

Computed

Derived value with auto-tracking dependencies.

from pyhmi import Observable
from pyhmi.core.binding import Computed

temp = Observable(22)
celsius = Computed(lambda: temp.value)
fahrenheit = Computed(lambda: temp.value * 9/5 + 32)

BindingEngine

Central binding manager. Use engine.binding_engine.

MethodDescription
define(name, value)Define observable or register widget
get(name)Get observable by name
get_widget(name)Get widget by ID
bind(widget, prop, expr)Bind property to expression
apply_binding(widget, prop, expr)Evaluate and apply binding

Expression syntax: {{ widget_id.property }} with optional prefix/suffix.

Animation Engine

Module: pyhmi.core.animation

Easing Enum

ValueDescription
LINEARConstant speed
EASE_INSlow start, fast end
EASE_OUTFast start, slow end
EASE_IN_OUTSlow start and end
BOUNCEBounce effect

Animation

Property animation with keyframes. Animated properties are passed as keyword arguments.

from pyhmi import Animation, Easing

engine.animation_engine.animate(
    widget,
    duration=1.0,
    easing=Easing.EASE_OUT,
    x=100,          # animate widget.x to 100
)
ParameterTypeDefaultDescription
targetWidgetBase | NoneNoneTarget widget
durationfloat1.0Duration in seconds
easingEasingLINEAREasing curve
delayfloat0.0Start delay in seconds
loopboolFalseLoop animation
keyframesList[Keyframe] | NoneNoneKeyframe timeline
**propertiesfloat—Target values per property

Keyframe

ParameterTypeDescription
timefloatNormalized time (0.0-1.0)
valuesDict[str, float]Property values at this keyframe
easingEasingEasing curve to this keyframe

AnimationEngine

MethodSignatureDescription
animate(target, duration, easing, delay, loop, keyframes, **properties) -> AnimationStart animation
update(dt: float) -> NoneUpdate all animations
stop_all() -> NoneStop all animations

Style Templates

Module: pyhmi.core.engine

Reusable style definitions with cascade support.

from pyhmi import StyleTemplate, Engine

template = StyleTemplate("dark_theme")
template.set(
    background_color=(30, 30, 30, 255),
    text_color=(255, 255, 255),
    font_size=14,
)
engine.register_template(template)
engine.set_active_template("dark_theme")
MethodDescription
set(**kwargs)Set style properties
apply(widget)Apply to widget

Accelerator Architecture

Modules: pyhmi.core.accelerator, pyhmi.backends.fb_accelerator

The pure-Python Painter is the always-correct reference implementation. Accelerators advertise a capability set and are registered per pixel buffer; the Painter delegates each primitive to the accelerator when supported and falls back to Python otherwise. Fallbacks are pixel-identical — enabling an accelerator only changes speed.

from pyhmi.backends.fb_accelerator import FbAccelerator

acc = FbAccelerator.create(buffer, width, height, color_format="rgb565_swapped")
# acc is None when the pyhmi_fb C core is not installed

Capability Constants

ConstantOperation
OP_SET_PIXELSet single pixel
OP_FILL_RECTFill rectangle
OP_LINELine
OP_CIRCLECircle
OP_ARCArc
OP_BLIT_GLYPHGlyph blit with 4-bit alpha LUT
OP_BLIT_IMAGEImage blit
OP_BLIT_ALPHA8Alpha-only (8-bit) blit with solid color
OP_CLEARClear buffer
ALL_OPSTuple of all operations

Accelerator (base class)

MemberDescription
capabilitiesSet of supported OP_* constants
supports(op)Check capability
register(buffer, acc)Register accelerator for a pixel buffer
get(buffer)Look up accelerator by buffer
clear(buffer)Remove registration

FbAccelerator

Wraps the portable C core pyhmi_fb (all drawing ops + blit_alpha8), with a per-color word cache. create() returns None when pyhmi_fb is unavailable. The display backends attach it automatically (display.accelerator).

Scene Management

Scene

Module: pyhmi.core.scene

Self-contained UI with widget tree, state, and lifecycle.

from pyhmi import Scene, WidgetBase

scene = Scene(name="dashboard", widget=root_widget)
scene.on_enter = lambda segue: print(f"Loaded with: {segue}")
scene.on_exit = lambda: {"user": "admin"}
PropertyTypeDescription
namestrScene identifier
widgetWidgetBaseRoot widget
file_pathstrPyHML file path
statedictScene state dict
on_enterCallableEnter callback (receives segue)
on_exitCallableExit callback (returns segue)

SceneManager

Module: pyhmi.core.scene

Scene navigation with history stack and transitions.

from pyhmi import SceneManager, Engine

manager = SceneManager(engine)

# Load scene
manager.load("dashboard.pyhml")

# Navigate forward with data
manager.push("settings.pyhml", segue={"user": "admin"})

# Go back with response
manager.pop(segue={"theme": "dark"})
MethodDescription
load(source, segue, transition)Load scene (file path, Scene, or WidgetBase)
push(source, segue, transition)Push onto history stack
pop(segue, transition)Pop and return to previous
navigate(name, scenes, segue, transition)Navigate to named scene
PropertyTypeDescription
current_sceneSceneActive scene
can_go_backboolHistory available
history_sizeintHistory stack size

Transition config: {"type": "fade"|"slide"|"none", "duration": 0.3, "direction": "right"}

SceneTransition

Module: pyhmi.core.scene

Transition animation between scenes.

PropertyTypeDescription
typestr"none", "fade", "slide"
durationfloatDuration in seconds
directionstr"left", "right", "up", "down"

Dialog System

DialogManager

Module: pyhmi.core.dialog

Modal and modeless dialog management.

from pyhmi import DialogManager, Engine

dlg = DialogManager(engine)

# Message dialog
dlg.show_message("Info", "Operation completed")

# Confirmation dialog
dlg.show_confirmation("Delete", "Are you sure?", callback=on_result)

# Input dialog
dlg.show_input("Name", "Enter your name:", callback=on_result)
MethodDescription
show(dialog, callback)Show dialog
hide()Hide active dialog
show_message(title, message, callback)Simple message
show_alert(title, message, callback)Warning alert
show_confirmation(title, message, callback)Yes/No confirm
show_input(title, message, placeholder, default, password, callback)Text input
PropertyTypeDescription
is_activeboolDialog currently showing

Dialog Types

ClassDescription
DialogMessageSimple OK message
DialogAlertWarning with OK
DialogConfirmYes/No confirmation
DialogInputText input with OK/Cancel
DialogCustomCustom content widget

DialogResult

PropertyTypeDescription
confirmedboolOK/Yes pressed
datadictReturned data

Custom Elements

CustomElement

Module: pyhmi.core.custom

Base class for user-defined widgets. Auto-registers with parser.

from pyhmi import CustomElement

class TemperatureGauge(CustomElement):
    value: float = 0.0
    unit: str = "C"

    def render(self, painter, x, y):
        painter.draw_rect(x, y, self.width, self.height, (50, 50, 50, 255))
        painter.draw_text(x + self.width//2, y + self.height//2,
                        f"{self.value}{self.unit}", 24, (255,255,255), "center")

Custom properties are auto-extracted from class attributes. Use element_name in subclass declaration for PyHML naming.

ElementRegistry

Module: pyhmi.core.custom

Singleton registry for custom elements.

from pyhmi import ElementRegistry, register_element

# Manual registration
ElementRegistry.get().register("TempGauge", TemperatureGauge)

# Decorator registration
@register_element("TempGauge")
class TemperatureGauge(CustomElement):
    pass
MethodDescription
get()Get singleton instance
register(name, cls)Register element
unregister(name)Remove element
get_class(name)Get class by name
is_registered(name)Check if registered
list_elements()List all names
reset()Reset registry (testing)

Display Backends

Sdl2Display

Module: pyhmi.backends.display

Cross-platform SDL2 rendering backend for development and testing.

from pyhmi import Sdl2Display, Engine

display = Sdl2Display(width=320, height=240, title="PyHMI Demo")
engine = Engine(display)
engine.run()
ParameterTypeDefaultDescription
widthint320Window width
heightint240Window height
titlestr"PyHMI"Window title

FramebufferDisplay

Module: pyhmi.backends.framebuffer

Linux framebuffer backend for direct /dev/fb0 rendering via mmap.

from pyhmi.backends.framebuffer import FramebufferDisplay
from pyhmi import Engine

display = FramebufferDisplay(path="/dev/fb0")
engine = Engine(display)
engine.run()
ParameterTypeDefaultDescription
pathstr"/dev/fb0"Framebuffer device path
widthint0Width (0 = read from device)
heightint0Height (0 = read from device)
titlestr"PyHMI"Logical title

Attaches the pyhmi_fb C accelerator automatically when available (display.accelerator).

CircuitPythonDisplay

Module: pyhmi.backends.circuitpython

CircuitPython SPI LCD backend for microcontrollers (displayio-compatible).

from pyhmi.backends.circuitpython import CircuitPythonDisplay
from pyhmi import Engine

display = CircuitPythonDisplay(
    width=240,
    height=240,
    controller="st7789",
    spi=spi,
    command=board.D25,
    chip_select=board.D24,
    reset=board.D23,
)
engine = Engine(display)
engine.run()
ParameterTypeDefaultDescription
widthint240Display width
heightint240Display height
titlestr"PyHMI MCU"Logical title
controllerstr"st7789"Panel controller
spiAnyNoneSPI bus instance
commandAnyNoneDC pin
chip_selectAnyNoneCS pin
resetAnyNoneRST pin
backlightAnyNoneBacklight pin
rotationint0Rotation (0/90/180/270)
offset_xint0Horizontal panel offset
offset_yint0Vertical panel offset

Supported controllers: st7735, st7789, ili9341, hx8357, st7262 (CircuitPythonDisplay.SUPPORTED_CONTROLLERS).

Graphics

Canvas

Module: pyhmi.backends.canvas

Double-buffered pixel array for low-level drawing.

PropertyTypeDescription
widthintCanvas width
heightintCanvas height
pixelsbytesRaw pixel data

Painter

Module: pyhmi.backends.canvas

Drawing primitives for widgets.

MethodSignatureDescription
draw_line(x1, y1, x2, y2, color, width=1)Bresenham line
draw_rect(x, y, w, h, color, filled=False, border_radius=0, border_width=1)Rectangle
draw_rounded_rect(x, y, w, h, color, filled=True, radius=0)Rounded rectangle
draw_circle(cx, cy, radius, color, filled=False)Midpoint circle
draw_arc(cx, cy, radius, start_angle, end_angle, color, width=2)Arc segment (radians)
draw_text(x, y, text, font_size=12, color=(255,255,255), alignment="left", font=None)Text rendering (y = baseline)
draw_image(x, y, image, w, h)Image blit
draw_shadow(x, y, w, h, radius=0, blur=4, alpha=30)Drop shadow
draw_gradient(x, y, w, h, color1, color2, vertical=True, radius=0)Linear gradient fill
blit_bytes(x, y, w, h, rgba)Bytes-native RGBA blit (delegates to C blit_image)
blit_pil(x, y, pil_image, width=0, height=0)Pillow image blit (delegates to blit_bytes)
text_width(text, font_size, font=None) -> intMeasured text width
text_height(font_size, font=None) -> intMeasured text height

Accelerated path: when the display target carries an accelerator (the pyhmi_fb C core), every primitive above delegates to C; otherwise a pixel-identical Python fallback runs. Alpha-only blitting (OP_BLIT_ALPHA8) is an accelerator operation exposed on FbAccelerator, not a Painter method.

Font System

Modules: pyhmi.core.font, pyhmi.core.ttf

Bitmap fonts (built-in Arimo, 4-bit grayscale anti-aliased) with optional dynamic TrueType.

FunctionSignatureDescription
get_default_font(size: int) -> FontCached bitmap font per size (10/12/14/16/20/24)
prewarm_fonts(sizes=(10,12,14,16,20,24)) -> NoneDecode glyph tables at boot (avoids render-time allocation on fragmented MCU heaps)

PureTTF (pyhmi.core.ttf)

Pure-Python TTF parser + rasterizer (no Pillow):

MemberSignatureDescription
PureTTF.from_file(path) -> PureTTFLoad a TTF file
render_char(ch, size) -> (pixels, w, h, advance, bx, by)Rasterize one glyph
metrics() -> dictFont metrics
load_ttf(path, size=14) -> dict | NoneFont dict: ascent/descent/line_height/glyphs/advance

Image Utilities

Module: pyhmi.core.image

Pure-Python PNG/BMP decode and PNG encode (zlib stdlib, no Pillow required).

Function / ClassDescription
SimpleImagePIL-compatible API subset: mode, width, height, convert, resize, load, tobytes, save, getpixel, open
decode_image(path)Decode PNG/BMP file to SimpleImage
save_png(path, w, h, rgba)Encode RGBA bytes to PNG

Parsers

PyHMLParser

Module: pyhmi.parsers.pyhml

Parses YAML-based PyHML files into widget trees.

from pyhmi import PyHMLParser, Engine

parser = PyHMLParser(engine)
root = parser.parse_file("dashboard.pyhml")
engine.set_root(root)

Features:

QMLImporter

Module: pyhmi.parsers.qml

Imports Qt QML files and converts to PyHMI widget trees. Parsed widgets are registered on the engine; the import methods return None.

from pyhmi import QMLImporter, Engine

importer = QMLImporter(engine)
importer.import_qml(qml_content)          # QML source string
importer.import_qml_file("dashboard.qml")  # QML file path

HTML Converter

Module: pyhmi.parsers.html

Converts HTML files to PyHML format.

from pyhmi.parsers import html_to_pyhml, convert_html_file

# Convert HTML string
pyhml = html_to_pyhml("<div><p>Hello</p></div>")

# Convert file
convert_html_file("page.html", "output.pyhml")

Widgets

Basic Widgets

Label

Module: pyhmi.widgets.label

Text display widget.

PropertyTypeDefaultDescription
textstr""Display text
font_sizeint12Font size
text_colorTuple[int,int,int](255,255,255)Text color
alignstr"left""left", "center", "right"

Button

Module: pyhmi.widgets.button

Clickable push button.

PropertyTypeDefaultDescription
textstr""Button label
background_colorRGBA(0,120,215,255)Background

Signals: Clicked

CheckBox

Module: pyhmi.widgets.checkbox

Toggle checkbox.

PropertyTypeDefaultDescription
textstr""Label text
checkedboolFalseChecked state

Signals: ValueChanged

RadioButton

Module: pyhmi.widgets.radiobutton

Exclusive selection button.

PropertyTypeDefaultDescription
textstr""Label text
checkedboolFalseChecked state

Signals: ValueChanged

Switch

Module: pyhmi.widgets.switch

Toggle switch widget.

PropertyTypeDefaultDescription
checkedboolFalseOn/off state
labelstr""Label drawn outside the bounds
left_hand_textboolFalseDraw label on the left instead of right

Signals: ValueChanged

Slider

Module: pyhmi.widgets.slider

Value slider with drag support.

PropertyTypeDefaultDescription
valuefloat0.0Current value
min_valuefloat0.0Minimum
max_valuefloat100.0Maximum
orientationstr"horizontal""horizontal" or "vertical"

Signals: ValueChanged

ProgressBar

Module: pyhmi.widgets.progressbar

Progress indicator bar.

PropertyTypeDefaultDescription
valuefloat0.0Current progress
min_valuefloat0.0Minimum
max_valuefloat100.0Maximum

Dial

Module: pyhmi.widgets.dial

Circular dial control.

PropertyTypeDefaultDescription
valuefloat0.0Current value
min_valuefloat0.0Minimum
max_valuefloat100.0Maximum

Signals: ValueChanged

Rotary

Module: pyhmi.widgets.rotary

Rotary knob control.

PropertyTypeDefaultDescription
valuefloat0.0Current angle
min_valuefloat0.0Minimum
max_valuefloat360.0Maximum

Signals: ValueChanged

Spinbox

Module: pyhmi.widgets.spinbox

Numeric input with spin buttons.

PropertyTypeDefaultDescription
valueint0Current value
min_valueint0Minimum
max_valueint100Maximum
stepint1Step size
easytouchboolFalseFinger layout: full-height minus/plus side buttons
labelstr""Label drawn outside the bounds
left_hand_textboolFalseDraw label on the left instead of right

Signals: ValueChanged

TextField

Module: pyhmi.widgets.textfield

Single-line text input.

PropertyTypeDefaultDescription
textstr""Current text
placeholderstr""Placeholder text
passwordboolFalseMasked input
cursor_posint0Cursor position

Signals: ValueChanged, FocusIn, FocusOut, Submitted

TextArea

Module: pyhmi.widgets.textarea

Multi-line text input.

PropertyTypeDefaultDescription
textstr""Current text
placeholderstr""Placeholder text

Signals: ValueChanged, FocusIn, FocusOut

Image

Module: pyhmi.widgets.image

Image display widget.

PropertyTypeDefaultDescription
sourcestr""Image file path
fill_modestr"stretch""stretch", "contain", "cover"

DropDown

Module: pyhmi.widgets.dropdown

Dropdown list widget — backward-compatible alias of ComboBox (DropDown = ComboBox).

PropertyTypeDefaultDescription
optionsList[str][]List items
selected_indexint-1Selected index

Signals: ValueChanged

ComboBox

Module: pyhmi.widgets.combobox

Combo box: dropdown selection, optionally with editable text input.

PropertyTypeDefaultDescription
textstr""Current text
editableboolFalseAllow custom text input
optionsList[str][]List items
selected_indexint-1Selected index
font_sizeint12Font size

Signals: ValueChanged

LED

Module: pyhmi.widgets.led

LED indicator widget.

PropertyTypeDefaultDescription
onboolFalseOn/off state
colorTuple[int,int,int](0,255,0)LED color

TableView

Module: pyhmi.widgets.tableView

Table data display.

PropertyTypeDefaultDescription
headersList[str][]Column headers
rowsList[List[Any]][]Data rows

TreeView

Module: pyhmi.widgets.treeView

Hierarchical tree display.

PropertyTypeDefaultDescription
itemsList[dict][]Tree items with label, children

Input Widgets

VirtualKeyboard

Module: pyhmi.widgets.virtualKeyboard

Touch-optimized virtual keyboard for small screens.

PropertyTypeDefaultDescription
layoutstr"qwerty""qwerty", "azerty"
modestr"text""text", "number", "email"
visibleboolFalseShow/hide

Signals: TextChanged, Submitted, Dismissed

Keyboard

Module: pyhmi.widgets.keyboard

Full virtual keyboard widget.

SearchField

Module: pyhmi.widgets.searchField

Search input field with icon.

ImageButton

Module: pyhmi.widgets.imageButton

Image-based button.

ButtonMatrix

Module: pyhmi.widgets.buttonMatrix

Grid of buttons (keypad style).

Roller

Module: pyhmi.widgets.roller

Scrolling selector wheel.

Tumbler

Module: pyhmi.widgets.tumbler

Spinnable wheel selector.

Wheel

Module: pyhmi.widgets.wheel

Scrolling wheel control.

Container Widgets

Container

Module: pyhmi.widgets.container

Generic grouping widget with layout support.

Frame

Module: pyhmi.widgets.frame

Visual frame container.

GroupBox

Module: pyhmi.widgets.groupBox

Grouped container with title.

ScrollView

Module: pyhmi.widgets.scrollView

Scrollable container.

SplitView

Module: pyhmi.widgets.splitView

Draggable splitter container.

StackView

Module: pyhmi.widgets.stackView

Stack-based navigation container.

SwipeView

Module: pyhmi.widgets.swipeView

Swipeable page container.

TabView

Module: pyhmi.widgets.tabView

Tabbed interface container.

TabBar

Module: pyhmi.widgets.tabBar

Tab bar widget.

TabButton

Module: pyhmi.widgets.tabButton

Tab button widget.

TileView

Module: pyhmi.widgets.tileView

Tiled view container.

Toolbar

Module: pyhmi.widgets.toolbar

Toolbar container.

Drawer

Module: pyhmi.widgets.drawer

Side panel drawer.

Menu

Module: pyhmi.widgets.menu

Popup menu.

MenuBar

Module: pyhmi.widgets.menuBar

Menu bar widget.

MenuItem

Module: pyhmi.widgets.menuItem

Menu item widget.

ContextMenu

Module: pyhmi.widgets.contextMenu

Right-click context menu.

Page

Module: pyhmi.widgets.page

Styled page container.

Pane

Module: pyhmi.widgets.pane

Styled pane container.

Chart Widgets

LineChart

Module: pyhmi.widgets.lineChart

Line chart widget.

PropertyTypeDefaultDescription
dataList[float][]Data points
x_labelsList[str][]X-axis labels

AreaChart

Module: pyhmi.widgets.areaChart

Area chart widget.

BarChart

Module: pyhmi.widgets.barChart

Bar chart widget.

Gauge

Module: pyhmi.widgets.gauge

Radial gauge widget.

PropertyTypeDefaultDescription
valuefloat0.0Current value
min_valuefloat0.0Minimum
max_valuefloat100.0Maximum
clockwiseboolTrueSweep direction
text_enableboolTrueShow value text
pointer_enableboolTrueShow needle
scale_widthint8Arc thickness in pixels

Arc

Module: pyhmi.widgets.arc

Circular arc (progress indicator).

Meter

Module: pyhmi.widgets.meter

Meter gauge widget.

Scale

Module: pyhmi.widgets.scale

Scale widget with tick marks.

ArcLabel

Module: pyhmi.widgets.arcLabel

Label following arc path.

Media Widgets

Canvas

Module: pyhmi.widgets.canvas

Pixel-level drawing surface.

Video

Module: pyhmi.widgets.video

Video player widget (desktop only).

GIF

Module: pyhmi.widgets.gif

Animated GIF player.

AnimationImage

Module: pyhmi.widgets.animationImage

Animation image sequence.

Lottie

Module: pyhmi.widgets.lottie

Lottie animation player.

Navigation Widgets

InfiniteList

Module: pyhmi.widgets.infiniteList

Infinite scrolling list.

PageIndicator

Module: pyhmi.widgets.pageIndicator

Page indicator dots.

Specialized Widgets

Calendar

Module: pyhmi.widgets.calendar

Calendar view widget.

QRCode

Module: pyhmi.widgets.qrcode

QR code display.

MarqueeText

Module: pyhmi.widgets.marqueeText

Scrolling text widget.

BusyIndicator

Module: pyhmi.widgets.busyIndicator

Loading/busy indicator.

Scroller

Module: pyhmi.widgets.scroller

Smartphone-like scrollbar.

Spinner

Module: pyhmi.widgets.spinner

Loading spinner animation.

MessageDialog

Module: pyhmi.widgets.messageDialog

Message dialog with multiple buttons (real Button children).

Tooltip

Module: pyhmi.widgets.tooltip

Dark rounded tooltip bubble, auto-width from text, hidden by default.

ColorPicker

Module: pyhmi.widgets.colorpicker

RGB color picker with three Slider children and preset swatches.

Popup

Module: pyhmi.widgets.popup

Group-container popup dialog with title bar, close button, and Escape handling.

FileDialog

Module: pyhmi.widgets.filedialog

File/folder picker dialog with real Button children, scrollbar, and mouse-wheel scrolling.

VirtualKeyboardInputDialog

Module: pyhmi.widgets.virtualkeyboarddialog

Modal keyboard input dialog: live text echo to a target TextField, Enter confirms, Escape or x cancels.

Texture3D

Module: pyhmi.widgets.texture3d

3D texture embedding.

Layout Enums

Module: pyhmi.core.layout

FlexDirection

Direction for Flex layout.

ValueDescription
ROWLeft-to-right axis
COLUMNTop-to-bottom axis

MainAxisAlignment

Alignment along the main axis.

ValueDescription
STARTAlign to start
ENDAlign to end
CENTERCenter alignment
SPACE_BETWEENEqual space between items
SPACE_AROUNDEqual space around items
SPACE_EVENLYEvenly distributed space

CrossAxisAlignment

Alignment along the cross axis.

ValueDescription
STARTAlign to start
ENDAlign to end
CENTERCenter alignment
STRETCHStretch to fill

GridAlignment

Alignment for grid cells.

ValueDescription
STARTAlign to start
ENDAlign to end
CENTERCenter alignment
STRETCHStretch to fill cell

Layout

Abstract base class for layout engines. Subclasses: FlexLayout, GridLayout.

MethodSignatureDescription
apply(widget: WidgetBase) -> NoneCompute and apply layout to children

Gesture Recognizer

Module: pyhmi.core.gesture

Detects swipe, pinch, tap, and long-press gestures from raw touch events.

from pyhmi.core.gesture import GestureRecognizer, SwipeDirection, PinchAction

gr = GestureRecognizer(swipe_threshold=40, long_press_duration=0.8)
gr.on_swipe(lambda dir, sx, sy, ex, ey: print(f"Swipe {dir}"))
gr.on_tap(lambda x, y: print(f"Tap at {x},{y}"))
gr.on_pinch(lambda action, scale, cx, cy: print(f"Pinch {action}"))
gr.on_long_press(lambda x, y: print(f"Long press at {x},{y}"))

# Feed touch events
gr.touch_start(0, 100, 200)
gr.touch_move(0, 150, 200)
gr.touch_end(0)

GestureRecognizer

ParameterTypeDefaultDescription
swipe_thresholdint40Min displacement (px) for swipe
swipe_max_timefloat0.5Max time (s) for swipe
tap_max_displacementint10Max movement (px) for tap
tap_max_timefloat0.3Max time (s) for tap
long_press_durationfloat0.8Duration (s) for long-press
pinch_thresholdfloat0.15Min scale change for pinch
MethodSignatureDescription
on_swipe(callback) -> NoneRegister swipe callback
on_pinch(callback) -> NoneRegister pinch callback
on_tap(callback) -> NoneRegister tap callback
on_long_press(callback) -> NoneRegister long-press callback
touch_start(id, x, y) -> NoneHandle touch start
touch_move(id, x, y) -> NoneHandle touch move
touch_end(id) -> NoneHandle touch end
check_long_press() -> NonePeriodically detect long-press

SwipeDirection

ValueDescription
LEFTSwipe left
RIGHTSwipe right
UPSwipe up
DOWNSwipe down

PinchAction

ValueDescription
INPinch to zoom in
OUTPinch to zoom out

TouchPoint

Tracks a single touch point over time.

PropertyTypeDescription
idintTouch point identifier
xfloatCurrent X position
yfloatCurrent Y position
start_xfloatInitial X position
start_yfloatInitial Y position
displacement_xfloatX displacement from start
displacement_yfloatY displacement from start
distancefloatTotal distance traveled
elapsedfloatTime since touch started (s)
historyListPosition history
MethodSignatureDescription
update(x, y) -> NoneUpdate position

Font System

Module: pyhmi.core.font

Font

Abstract base class for fonts. Subclasses: BitmapFont.

PropertyTypeDescription
sizeintFont size in pixels
namestrFont name
ascentintAscent in pixels
descentintDescent in pixels
line_heightintLine height in pixels
MethodSignatureDescription
glyph_width(ch: str) -> intAdvance width for character
glyph_bitmap(ch: str) -> Tuple4-bit grayscale bitmap for glyph
text_width(text: str) -> intTotal pixel width of text

BitmapFont

Bitmap font from pre-converted TTF data (Arimo, 6 sizes, 4-bit grayscale AA).

from pyhmi import BitmapFont

font = BitmapFont(size=14, name="Arimo")
width = font.text_width("Hello")
MethodSignatureDescription
glyph_width(ch: str) -> intAdvance width for character
glyph_bitmap(ch: str) -> TupleBitmap data for glyph

TTFLoader

Dynamic TTF font loading via Pillow (PIL). Converts TTF to bitmap glyphs at runtime.

from pyhmi import TTFLoader

font = TTFLoader.load("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", size=14)
path = TTFLoader.find_font("Arimo")
MethodSignatureDescription
load(ttf_path: str, size: int) -> BitmapFontLoad TTF and convert to bitmap
find_font(name: str) -> str | NoneSearch system paths for font

Event Class

Module: pyhmi.core.event

Event object passed to handlers during bubbling.

from pyhmi import Event, EventType

event = Event(EventType.CLICK, target=button, x=10, y=20)
PropertyTypeDescription
typeEventTypeEvent type
targetWidgetBaseOriginating widget
current_targetWidgetBaseCurrent propagation target
propagateboolContinue bubbling
datadictArbitrary event data

EventSystem

Central event dispatcher. Use engine.event_system.

MethodSignatureDescription
on_global(event_type, handler) -> NoneRegister global handler
dispatch(event: Event) -> NoneDispatch event to target

Keyframe

Module: pyhmi.core.animation

Single animation keyframe with property values and easing.

from pyhmi import Easing
from pyhmi.core.animation import Keyframe

kf = Keyframe(time=0.5, values={"x": 100, "opacity": 0.5}, easing=Easing.EASE_OUT)
PropertyTypeDescription
timefloatNormalized time (0.0-1.0)
valuesDict[str, float]Property values at this keyframe
easingEasingEasing curve to this keyframe

StyleTemplate

Module: pyhmi.core.engine

Reusable style definitions with cascade support.

from pyhmi import StyleTemplate

template = StyleTemplate("dark_theme")
template.set(background_color=(30, 30, 30, 255), text_color=(255, 255, 255), font_size=14)
template.apply(widget)
MethodSignatureDescription
set(**kwargs) -> NoneSet style properties
apply(widget: WidgetBase) -> NoneApply template to widget

DialogBase

Module: pyhmi.core.dialog

Base class for all dialogs. Subclasses: DialogMessage, DialogAlert, DialogConfirm, DialogInput, DialogCustom.

PropertyTypeDescription
titlestrDialog title
modalboolModal flag
MethodSignatureDescription
set_callback(callback) -> NoneSet result callback
confirm(data: dict) -> NoneConfirm dialog
dismiss() -> NoneDismiss dialog

DialogOverlay

Semi-transparent overlay for modal dialogs. Blocks interaction with background.

PropertyTypeDescription
background_colorRGBASemi-transparent black
opacityfloatOverlay opacity

HTML Parser Classes

Module: pyhmi.parsers.html

HTMLParserConverter

Parse HTML and convert to PyHML format. Maps HTML tags to PyHMI widgets, CSS to style templates, and JS events to signal handlers.

from pyhmi.parsers.html import HTMLParserConverter

parser = HTMLParserConverter()
parser.pre_extract(html_content)
parser.feed(html_content)
pyhml = parser.to_pyhml()
MethodSignatureDescription
pre_extract(html_content: str) -> NoneExtract CSS and JS before parsing
feed(data: str) -> NoneFeed HTML data
to_pyhml() -> strReturn converted PyHML string

CSSClassExtractor

Extract CSS class definitions from <style> tags.

PropertyTypeDescription
css_blockslist[str]Extracted CSS blocks

JSExtractor

Extract JavaScript event handlers from <script> tags.

PropertyTypeDescription
handlersdictExtracted event handlers
MethodSignatureDescription
get_handlers_for_element(element_id: str) -> dictGet handlers for element ID

Input Backends

InputBackend

Module: pyhmi.backends.input

Protocol for input backends. Defines the interface for polling input devices and dispatching events.

MethodSignatureDescription
set_tree(tree: WidgetTree) -> NoneSet widget tree for dispatch
poll() -> NonePoll devices and dispatch events

Sdl2Input

Module: pyhmi.backends.input

SDL2 input backend for keyboard, mouse, and touch. Polls SDL events and dispatches to the widget tree.

from pyhmi import Sdl2Input, Engine

input_backend = Sdl2Input(engine=engine)
input_backend.set_tree(engine.tree)
input_backend.set_display(display)
MethodSignatureDescription
set_tree(tree: WidgetTree) -> NoneSet widget tree
set_display(display) -> NoneSet display backend
poll() -> NonePoll SDL events

EvdevInput

Module: pyhmi.backends.evdev_input

Linux evdev input backend. Polls evdev devices and dispatches events to the widget tree. Supports keyboards, mice, and touchscreens.

from pyhmi.backends.evdev_input import EvdevInput

input_backend = EvdevInput(engine=engine)
input_backend.auto_detect_devices()
input_backend.add_device("/dev/input/event0")
input_backend.set_tree(engine.tree)
input_backend.set_display_size(480, 320)
MethodSignatureDescription
set_tree(tree) -> NoneSet widget tree for dispatch
set_display_size(width, height) -> NoneSet display size for scaling
add_device(path: str) -> NoneAdd evdev device
auto_detect_devices() -> NoneAuto-detect available devices
poll() -> NonePoll all devices
PropertyTypeDescription
mouse_positionTuple[int, int]Current mouse position

EvdevDevice

Module: pyhmi.backends.evdev_input

Wrapper for a single evdev input device. Auto-classifies as touchscreen, mouse, or keyboard.

PropertyTypeDescription
pathstrDevice path
namestrDevice name

CircuitPythonDisplay

Module: pyhmi.backends.circuitpython

CircuitPython SPI LCD display backend. Supports ST7735, ST7789, ILI9341, and HX8357 controllers. Falls back to software buffer on desktop.

from pyhmi import CircuitPythonDisplay

display = CircuitPythonDisplay(width=240, height=240, controller="st7789")
display.initialize()
buffer = display.get_pixel_buffer()
display.flip()
display.capture_framebuffer("screenshot.png")
ParameterTypeDefaultDescription
widthint240Display width
heightint240Display height
controllerstr"st7789"Controller type
rotationint0Display rotation
MethodSignatureDescription
initialize() -> NoneInitialize display
resize(width, height) -> NoneResize display
get_pixel_buffer() -> array.arrayGet back buffer
flip() -> NonePresent back buffer
capture_framebuffer(path: str) -> NoneSave framebuffer to PNG
quit() -> NoneClean up resources
set_pixel(x, y, color) -> NoneSet single pixel
PropertyTypeDescription
rendererNoneMCU uses pixel buffer, not renderer

Additional Widgets

Window

Module: pyhmi.widgets.window

Top-level window container. Root widget for PyHML scenes.

PropertyTypeDefaultDescription
titlestr"PyHMI Window"Window title
widthint320Window width
heightint240Window height
background_colorRGBA(247,248,250,255)Background color
layoutLayout | NoneNoneLayout engine

List

Module: pyhmi.widgets.list

Simple list container with selection support.

PropertyTypeDefaultDescription
itemslist["Item 1", ...]List items
selected_indexint-1Selected item index
font_sizeint12Font size

Signals: ValueChanged

ListView

Module: pyhmi.widgets.listview

Scrollable list view with drag-to-scroll support.

PropertyTypeDefaultDescription
itemslist["Item 1", ...]List items
selected_indexint-1Selected item index
font_sizeint12Font size

Signals: ValueChanged

ScrollBar

Module: pyhmi.widgets.scrollbar

Scrollbar widget for scrollable content. Supports vertical and horizontal orientation.

PropertyTypeDefaultDescription
valuefloat0.0Current scroll position
min_valuefloat0.0Minimum value
max_valuefloat100.0Maximum value
page_sizefloat20.0Visible page size
orientationstr"vertical""vertical" or "horizontal"

Signals: ValueChanged

VideoDecoder

Module: pyhmi.widgets.video

Video decoder supporting MP4 and MJPEG formats via Pillow.

PropertyTypeDescription
sourcestrVideo file path or URL
fpsfloatTarget frames per second
framesList[VideoFrame]Decoded frames
total_framesintFrame count
durationfloatDuration in seconds
is_loadedboolSuccessfully loaded
errorstr | NoneError message
MethodSignatureDescription
get_frame(index: int) -> VideoFrame | NoneGet frame by index

VideoFrame

Module: pyhmi.widgets.video

A single decoded video frame.

PropertyTypeDescription
pixelsList[int]Pixel data
widthintFrame width
heightintFrame height

CLI Tools

Project Generator

Module: pyhmi.cli.generator

CLI tool for generating PyHMI project scaffolding.

# Simple mode (2 questions)
python -m pyhmi.cli.generator --simple myproject

# Advanced mode (8 questions)
python -m pyhmi.cli.generator --advanced myproject

Generated files:

Advanced mode questions:

  1. Target platform (linux, mcu, desktop)
  2. Display width
  3. Display height
  4. Backends (sdl2, framebuffer, spi_lcd)
  5. Input devices (keyboard, mouse, touch)
  6. Scene count
  7. Theme (dark, light, custom)
  8. Project description
  9. Include examples (y/n)

Console Scripts

Registered in pyproject.toml:

CommandEntry PointDescription
pyhmi-genpyhmi.cli.generator:mainProject generator (simple / advanced wizard)
pyhmi-editorpyhmi.cli.editor.main:mainCross-platform UI Scene Editor (SDL2)
pyhmi-runpyhmi.cli.runner:mainPyHMI Runner — drag & drop a folder, .py or .pyhml scene to run it
pyhmi-emulatorpyhmi.cli.emulator:mainStandalone PyHML scene emulator window

Additional CLI modules (run via python -m):

ModuleDescription
pyhmi.cli.font_generatorConvert TTF to 4-bit grayscale bitmap font modules
pyhmi.cli.pyhml_to_standaloneConvert a PyHML project to a single standalone Python file
pyhmi.cli.bench_memoryMemory benchmark
pyhmi.cli.bench_fpsFPS benchmark