PyHMI API Reference

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

Version: 0.1.0 | 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)

Constructor

ParameterTypeDescription
displayDisplayBackendDisplay backend instance

Properties

PropertyTypeDescription
displayDisplayBackendActive display backend
event_systemEventSystemGlobal event system
binding_engineBindingEngineData binding engine
animation_engineAnimationEngineAnimation engine
treeWidgetTreeRoot widget tree

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
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)
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_resize(width: int, height: int) -> NoneDispatch resize

Event System

Module: pyhmi.core.event

EventType Enum

ValueDescription
CLICKMouse/touch click
TOUCH_PRESSTouch down
TOUCH_RELEASETouch up
TOUCH_DRAGTouch move
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, 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.

from pyhmi import Animation, Easing

anim = Animation(
    target=widget,
    property_name="x",
    from_value=0,
    to_value=100,
    duration=1.0,
    easing=Easing.EASE_OUT,
)
engine.animation_engine.animate(anim)
ParameterTypeDefaultDescription
targetWidgetBaseTarget widget
property_namestrProperty to animate
from_valueAnyCurrent valueStart value
to_valueAnyEnd value
durationfloat1.0Duration in seconds
easingEasingLINEAREasing curve
delayfloat0.0Start delay
loopboolFalseLoop animation

AnimationEngine

MethodDescription
animate(animation)Start animation
update(dt)Update all animations
stop_all()Stop 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

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

Linux framebuffer backend for direct /dev/fb0 rendering.

from pyhmi import FramebufferDisplay, Engine

display = FramebufferDisplay(device="/dev/fb0")
engine = Engine(display)
engine.run()

SpiLcdDisplay

Module: pyhmi.backends.display

CircuitPython SPI LCD backend for microcontrollers.

from pyhmi import SpiLcdDisplay, Engine

display = SpiLcdDisplay(
    driver=display_instance,  # displayio-compatible
    color_format="rgb565",
)
engine = Engine(display)
engine.run()

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)Bresenham line
draw_rect(x, y, w, h, color, fill, border_width)Rectangle
draw_circle(cx, cy, radius, color, fill)Midpoint circle
draw_arc(cx, cy, radius, start, end, color, width)Arc segment
draw_text(x, y, text, size, color, align)Text rendering
draw_image(x, y, image, w, h)Image blit

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.

from pyhmi import QMLImporter, Engine

importer = QMLImporter(engine)
root = importer.import_qml("dashboard.qml")

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

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

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.

PropertyTypeDefaultDescription
itemsList[str][]List items
selectedint0Selected index

Signals: ValueChanged

ComboBox

Module: pyhmi.widgets.combobox

Combo box with editable input.

PropertyTypeDefaultDescription
itemsList[str][]List items
selectedint0Selected index
editableboolTrueAllow custom input

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

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

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 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 Keyframe, Easing

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