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
| Parameter | Type | Description |
|---|---|---|
display | DisplayBackend | Display backend instance |
Properties
| Property | Type | Description |
|---|---|---|
display | DisplayBackend | Active display backend |
event_system | EventSystem | Global event system |
binding_engine | BindingEngine | Data binding engine |
animation_engine | AnimationEngine | Animation engine |
tree | WidgetTree | Root widget tree |
Methods
| Method | Signature | Description |
|---|---|---|
set_root | (widget: WidgetBase) -> None | Set the root widget |
set_layout | (layout: Layout) -> None | Set the layout engine |
register_template | (template: StyleTemplate) -> None | Register a style template |
set_active_template | (name: str) -> None | Activate a theme template |
add_frame_callback | (callback: Callable[[float], None]) -> None | Add per-frame callback |
run | () -> None | Start the main event loop |
stop | () -> None | Stop the event loop |
resize | (width: int, height: int) -> None | Handle 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
| Property | Type | Default | Description |
|---|---|---|---|
id | str | None | None | Unique identifier |
x | int | 0 | X position |
y | int | 0 | Y position |
width | int | 0 | Width in pixels |
height | int | 0 | Height in pixels |
visible | bool | True | Visibility flag |
enabled | bool | True | Interaction enabled |
checked | bool | False | Checked state (toggles) |
focused | bool | False | Keyboard focus |
text | str | "" | Display text |
background_color | Tuple[int,int,int,int] | (0,0,0,0) | RGBA background |
text_color | Tuple[int,int,int] | (255,255,255) | RGB text color |
font_size | int | 12 | Font size in pixels |
border_width | int | 0 | Border width |
border_color | Tuple[int,int,int] | (128,128,128) | Border color |
border_radius | int | 0 | Border corner radius |
padding | int | 0 | Internal padding |
margin | int | 0 | External margin |
opacity | float | 1.0 | Opacity (0.0-1.0) |
parent | WidgetBase | None | None | Read-only parent |
children | List[WidgetBase] | [] | Read-only children list |
style_template | str | None | None | Applied template name |
Methods
| Method | Signature | Description |
|---|---|---|
add_child | (child: WidgetBase) -> None | Add child widget |
remove_child | (child: WidgetBase) -> None | Remove child widget |
on | (event_type: EventType, handler: Callable) -> None | Register event handler |
on_signal | (signal_name: str, handler: Callable) -> None | Register named signal handler |
on_event | (event: Event) -> bool | Handle incoming event (override) |
emit | (event: Event | str, data: dict) -> None | Emit event or signal |
render | (surface: Any, x: int, y: int) -> None | Render widget (override) |
update | (dt: float) -> None | Update state (override) |
render_recursive | (surface, x, y) -> None | Render self + children |
hit_test | (mx: int, my: int) -> WidgetBase | None | Point hit detection |
contains_point | (mx: int, my: int) -> bool | Bounds check |
Class Attributes
| Attribute | Type | Description |
|---|---|---|
registry | Dict[str, type] | Auto-registered subclasses |
WidgetTree
Module: pyhmi.core.tree
Hierarchical widget model with layout computation, coordinated rendering, and event dispatch.
| Method | Signature | Description |
|---|---|---|
set_root | (widget: WidgetBase) -> None | Set root widget |
set_layout | (layout: Layout) -> None | Set layout engine |
compute_layout | () -> None | Compute positions for all widgets |
render | (surface: Any) -> None | Render entire tree |
update | (dt: float) -> None | Update all widgets |
traverse | () -> List[WidgetBase] | Depth-first traversal |
handle_click | (x: int, y: int) -> None | Dispatch click event |
handle_touch_press | (x: int, y: int) -> None | Dispatch touch press |
handle_touch_release | (x: int, y: int) -> None | Dispatch touch release |
handle_key_press | (key: str, mod: int) -> None | Dispatch key press |
handle_resize | (width: int, height: int) -> None | Dispatch resize |
Event System
Module: pyhmi.core.event
EventType Enum
| Value | Description |
|---|---|
CLICK | Mouse/touch click |
TOUCH_PRESS | Touch down |
TOUCH_RELEASE | Touch up |
TOUCH_DRAG | Touch move |
KEY_PRESS | Key press |
VALUE_CHANGED | Value change |
FOCUS_IN | Focus gained |
FOCUS_OUT | Focus lost |
RESIZE | Widget resized |
CUSTOM | Custom event |
Event Class
| Property | Type | Description |
|---|---|---|
type | EventType | Event type |
target | WidgetBase | Originating widget |
current_target | WidgetBase | Current propagation target |
propagate | bool | Continue bubbling (default True) |
data | dict | Arbitrary 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,
)
| Parameter | Type | Default | Description |
|---|---|---|---|
direction | str | "row" | "row" or "column" |
main_alignment | str | "start" | "start", "center", "end", "space_between" |
cross_alignment | str | "start" | "start", "center", "end", "stretch" |
spacing | int | 0 | Pixel spacing between children |
wrap | bool | False | Allow wrapping |
GridLayout
Grid layout with rows, columns, span, and alignment.
from pyhmi import GridLayout
layout = GridLayout(
columns=3,
rows=2,
spacing=5,
alignment="center",
)
| Parameter | Type | Default | Description |
|---|---|---|---|
columns | int | 1 | Number of columns |
rows | int | 1 | Number of rows |
spacing | int | 0 | Pixel spacing |
alignment | str | "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"
| Method | Description |
|---|---|
subscribe(callback) | Subscribe to value changes |
watch(callback) | Watch with old/new values |
value | Get/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.
| Method | Description |
|---|---|
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
| Value | Description |
|---|---|
LINEAR | Constant speed |
EASE_IN | Slow start, fast end |
EASE_OUT | Fast start, slow end |
EASE_IN_OUT | Slow start and end |
BOUNCE | Bounce 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)
| Parameter | Type | Default | Description |
|---|---|---|---|
target | WidgetBase | — | Target widget |
property_name | str | — | Property to animate |
from_value | Any | Current value | Start value |
to_value | Any | — | End value |
duration | float | 1.0 | Duration in seconds |
easing | Easing | LINEAR | Easing curve |
delay | float | 0.0 | Start delay |
loop | bool | False | Loop animation |
AnimationEngine
| Method | Description |
|---|---|
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")
| Method | Description |
|---|---|
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"}
| Property | Type | Description |
|---|---|---|
name | str | Scene identifier |
widget | WidgetBase | Root widget |
file_path | str | PyHML file path |
state | dict | Scene state dict |
on_enter | Callable | Enter callback (receives segue) |
on_exit | Callable | Exit 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"})
| Method | Description |
|---|---|
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 |
| Property | Type | Description |
|---|---|---|
current_scene | Scene | Active scene |
can_go_back | bool | History available |
history_size | int | History stack size |
Transition config: {"type": "fade"|"slide"|"none", "duration": 0.3, "direction": "right"}
SceneTransition
Module: pyhmi.core.scene
Transition animation between scenes.
| Property | Type | Description |
|---|---|---|
type | str | "none", "fade", "slide" |
duration | float | Duration in seconds |
direction | str | "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)
| Method | Description |
|---|---|
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 |
| Property | Type | Description |
|---|---|---|
is_active | bool | Dialog currently showing |
Dialog Types
| Class | Description |
|---|---|
DialogMessage | Simple OK message |
DialogAlert | Warning with OK |
DialogConfirm | Yes/No confirmation |
DialogInput | Text input with OK/Cancel |
DialogCustom | Custom content widget |
DialogResult
| Property | Type | Description |
|---|---|---|
confirmed | bool | OK/Yes pressed |
data | dict | Returned 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
| Method | Description |
|---|---|
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()
| Parameter | Type | Default | Description |
|---|---|---|---|
width | int | 320 | Window width |
height | int | 240 | Window height |
title | str | "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.
| Property | Type | Description |
|---|---|---|
width | int | Canvas width |
height | int | Canvas height |
pixels | bytes | Raw pixel data |
Painter
Module: pyhmi.backends.canvas
Drawing primitives for widgets.
| Method | Signature | Description |
|---|---|---|
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:
- Component hierarchy via YAML nesting
- Property assignment (type-coerced)
- Signal handlers (
on<SignalName>) - ID references for binding
- Layout declarations (
Column,Row,Grid) - Data binding with
{{ }}syntax - Custom element support
- Children list for duplicate widget types
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.
| Property | Type | Default | Description |
|---|---|---|---|
text | str | "" | Display text |
font_size | int | 12 | Font size |
text_color | Tuple[int,int,int] | (255,255,255) | Text color |
align | str | "left" | "left", "center", "right" |
Button
Module: pyhmi.widgets.button
Clickable push button.
| Property | Type | Default | Description |
|---|---|---|---|
text | str | "" | Button label |
background_color | RGBA | (0,120,215,255) | Background |
Signals: Clicked
CheckBox
Module: pyhmi.widgets.checkbox
Toggle checkbox.
| Property | Type | Default | Description |
|---|---|---|---|
text | str | "" | Label text |
checked | bool | False | Checked state |
Signals: ValueChanged
RadioButton
Module: pyhmi.widgets.radiobutton
Exclusive selection button.
| Property | Type | Default | Description |
|---|---|---|---|
text | str | "" | Label text |
checked | bool | False | Checked state |
Signals: ValueChanged
Switch
Module: pyhmi.widgets.switch
Toggle switch widget.
| Property | Type | Default | Description |
|---|---|---|---|
checked | bool | False | On/off state |
Signals: ValueChanged
Slider
Module: pyhmi.widgets.slider
Value slider with drag support.
| Property | Type | Default | Description |
|---|---|---|---|
value | float | 0.0 | Current value |
min_value | float | 0.0 | Minimum |
max_value | float | 100.0 | Maximum |
orientation | str | "horizontal" | "horizontal" or "vertical" |
Signals: ValueChanged
ProgressBar
Module: pyhmi.widgets.progressbar
Progress indicator bar.
| Property | Type | Default | Description |
|---|---|---|---|
value | float | 0.0 | Current progress |
min_value | float | 0.0 | Minimum |
max_value | float | 100.0 | Maximum |
Dial
Module: pyhmi.widgets.dial
Circular dial control.
| Property | Type | Default | Description |
|---|---|---|---|
value | float | 0.0 | Current value |
min_value | float | 0.0 | Minimum |
max_value | float | 100.0 | Maximum |
Signals: ValueChanged
Rotary
Module: pyhmi.widgets.rotary
Rotary knob control.
| Property | Type | Default | Description |
|---|---|---|---|
value | float | 0.0 | Current angle |
min_value | float | 0.0 | Minimum |
max_value | float | 360.0 | Maximum |
Signals: ValueChanged
Spinbox
Module: pyhmi.widgets.spinbox
Numeric input with spin buttons.
| Property | Type | Default | Description |
|---|---|---|---|
value | int | 0 | Current value |
min_value | int | 0 | Minimum |
max_value | int | 100 | Maximum |
step | int | 1 | Step size |
Signals: ValueChanged
TextField
Module: pyhmi.widgets.textfield
Single-line text input.
| Property | Type | Default | Description |
|---|---|---|---|
text | str | "" | Current text |
placeholder | str | "" | Placeholder text |
password | bool | False | Masked input |
cursor_pos | int | 0 | Cursor position |
Signals: ValueChanged, FocusIn, FocusOut, Submitted
TextArea
Module: pyhmi.widgets.textarea
Multi-line text input.
| Property | Type | Default | Description |
|---|---|---|---|
text | str | "" | Current text |
placeholder | str | "" | Placeholder text |
Signals: ValueChanged, FocusIn, FocusOut
Image
Module: pyhmi.widgets.image
Image display widget.
| Property | Type | Default | Description |
|---|---|---|---|
source | str | "" | Image file path |
fill_mode | str | "stretch" | "stretch", "contain", "cover" |
DropDown
Module: pyhmi.widgets.dropdown
Dropdown list widget.
| Property | Type | Default | Description |
|---|---|---|---|
items | List[str] | [] | List items |
selected | int | 0 | Selected index |
Signals: ValueChanged
ComboBox
Module: pyhmi.widgets.combobox
Combo box with editable input.
| Property | Type | Default | Description |
|---|---|---|---|
items | List[str] | [] | List items |
selected | int | 0 | Selected index |
editable | bool | True | Allow custom input |
Signals: ValueChanged
LED
Module: pyhmi.widgets.led
LED indicator widget.
| Property | Type | Default | Description |
|---|---|---|---|
on | bool | False | On/off state |
color | Tuple[int,int,int] | (0,255,0) | LED color |
TableView
Module: pyhmi.widgets.tableview
Table data display.
| Property | Type | Default | Description |
|---|---|---|---|
headers | List[str] | [] | Column headers |
rows | List[List[Any]] | [] | Data rows |
TreeView
Module: pyhmi.widgets.treeview
Hierarchical tree display.
| Property | Type | Default | Description |
|---|---|---|---|
items | List[dict] | [] | Tree items with label, children |
Input Widgets
VirtualKeyboard
Module: pyhmi.widgets.virtualkeyboard
Touch-optimized virtual keyboard for small screens.
| Property | Type | Default | Description |
|---|---|---|---|
layout | str | "qwerty" | "qwerty", "azerty" |
mode | str | "text" | "text", "number", "email" |
visible | bool | False | Show/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.
| Property | Type | Default | Description |
|---|---|---|---|
data | List[float] | [] | Data points |
x_labels | List[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.
| Property | Type | Default | Description |
|---|---|---|---|
value | float | 0.0 | Current value |
min_value | float | 0.0 | Minimum |
max_value | float | 100.0 | Maximum |
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.
| Value | Description |
|---|---|
ROW | Left-to-right axis |
COLUMN | Top-to-bottom axis |
MainAxisAlignment
Alignment along the main axis.
| Value | Description |
|---|---|
START | Align to start |
END | Align to end |
CENTER | Center alignment |
SPACE_BETWEEN | Equal space between items |
SPACE_AROUND | Equal space around items |
SPACE_EVENLY | Evenly distributed space |
CrossAxisAlignment
Alignment along the cross axis.
| Value | Description |
|---|---|
START | Align to start |
END | Align to end |
CENTER | Center alignment |
STRETCH | Stretch to fill |
GridAlignment
Alignment for grid cells.
| Value | Description |
|---|---|
START | Align to start |
END | Align to end |
CENTER | Center alignment |
STRETCH | Stretch to fill cell |
Layout
Abstract base class for layout engines. Subclasses: FlexLayout, GridLayout.
| Method | Signature | Description |
|---|---|---|
apply | (widget: WidgetBase) -> None | Compute 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
| Parameter | Type | Default | Description |
|---|---|---|---|
swipe_threshold | int | 40 | Min displacement (px) for swipe |
swipe_max_time | float | 0.5 | Max time (s) for swipe |
tap_max_displacement | int | 10 | Max movement (px) for tap |
tap_max_time | float | 0.3 | Max time (s) for tap |
long_press_duration | float | 0.8 | Duration (s) for long-press |
pinch_threshold | float | 0.15 | Min scale change for pinch |
| Method | Signature | Description |
|---|---|---|
on_swipe | (callback) -> None | Register swipe callback |
on_pinch | (callback) -> None | Register pinch callback |
on_tap | (callback) -> None | Register tap callback |
on_long_press | (callback) -> None | Register long-press callback |
touch_start | (id, x, y) -> None | Handle touch start |
touch_move | (id, x, y) -> None | Handle touch move |
touch_end | (id) -> None | Handle touch end |
check_long_press | () -> None | Periodically detect long-press |
SwipeDirection
| Value | Description |
|---|---|
LEFT | Swipe left |
RIGHT | Swipe right |
UP | Swipe up |
DOWN | Swipe down |
PinchAction
| Value | Description |
|---|---|
IN | Pinch to zoom in |
OUT | Pinch to zoom out |
TouchPoint
Tracks a single touch point over time.
| Property | Type | Description |
|---|---|---|
id | int | Touch point identifier |
x | float | Current X position |
y | float | Current Y position |
start_x | float | Initial X position |
start_y | float | Initial Y position |
displacement_x | float | X displacement from start |
displacement_y | float | Y displacement from start |
distance | float | Total distance traveled |
elapsed | float | Time since touch started (s) |
history | List | Position history |
| Method | Signature | Description |
|---|---|---|
update | (x, y) -> None | Update position |
Font System
Module: pyhmi.core.font
Font
Abstract base class for fonts. Subclasses: BitmapFont.
| Property | Type | Description |
|---|---|---|
size | int | Font size in pixels |
name | str | Font name |
ascent | int | Ascent in pixels |
descent | int | Descent in pixels |
line_height | int | Line height in pixels |
| Method | Signature | Description |
|---|---|---|
glyph_width | (ch: str) -> int | Advance width for character |
glyph_bitmap | (ch: str) -> Tuple | 4-bit grayscale bitmap for glyph |
text_width | (text: str) -> int | Total 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")
| Method | Signature | Description |
|---|---|---|
glyph_width | (ch: str) -> int | Advance width for character |
glyph_bitmap | (ch: str) -> Tuple | Bitmap 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")
| Method | Signature | Description |
|---|---|---|
load | (ttf_path: str, size: int) -> BitmapFont | Load TTF and convert to bitmap |
find_font | (name: str) -> str | None | Search 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)
| Property | Type | Description |
|---|---|---|
type | EventType | Event type |
target | WidgetBase | Originating widget |
current_target | WidgetBase | Current propagation target |
propagate | bool | Continue bubbling |
data | dict | Arbitrary event data |
EventSystem
Central event dispatcher. Use engine.event_system.
| Method | Signature | Description |
|---|---|---|
on_global | (event_type, handler) -> None | Register global handler |
dispatch | (event: Event) -> None | Dispatch 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)
| Property | Type | Description |
|---|---|---|
time | float | Normalized time (0.0-1.0) |
values | Dict[str, float] | Property values at this keyframe |
easing | Easing | Easing 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)
| Method | Signature | Description |
|---|---|---|
set | (**kwargs) -> None | Set style properties |
apply | (widget: WidgetBase) -> None | Apply template to widget |
DialogBase
Module: pyhmi.core.dialog
Base class for all dialogs. Subclasses: DialogMessage, DialogAlert, DialogConfirm, DialogInput, DialogCustom.
| Property | Type | Description |
|---|---|---|
title | str | Dialog title |
modal | bool | Modal flag |
| Method | Signature | Description |
|---|---|---|
set_callback | (callback) -> None | Set result callback |
confirm | (data: dict) -> None | Confirm dialog |
dismiss | () -> None | Dismiss dialog |
DialogOverlay
Semi-transparent overlay for modal dialogs. Blocks interaction with background.
| Property | Type | Description |
|---|---|---|
background_color | RGBA | Semi-transparent black |
opacity | float | Overlay 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()
| Method | Signature | Description |
|---|---|---|
pre_extract | (html_content: str) -> None | Extract CSS and JS before parsing |
feed | (data: str) -> None | Feed HTML data |
to_pyhml | () -> str | Return converted PyHML string |
CSSClassExtractor
Extract CSS class definitions from <style> tags.
| Property | Type | Description |
|---|---|---|
css_blocks | list[str] | Extracted CSS blocks |
JSExtractor
Extract JavaScript event handlers from <script> tags.
| Property | Type | Description |
|---|---|---|
handlers | dict | Extracted event handlers |
| Method | Signature | Description |
|---|---|---|
get_handlers_for_element | (element_id: str) -> dict | Get 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.
| Method | Signature | Description |
|---|---|---|
set_tree | (tree: WidgetTree) -> None | Set widget tree for dispatch |
poll | () -> None | Poll 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)
| Method | Signature | Description |
|---|---|---|
set_tree | (tree: WidgetTree) -> None | Set widget tree |
set_display | (display) -> None | Set display backend |
poll | () -> None | Poll 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)
| Method | Signature | Description |
|---|---|---|
set_tree | (tree) -> None | Set widget tree for dispatch |
set_display_size | (width, height) -> None | Set display size for scaling |
add_device | (path: str) -> None | Add evdev device |
auto_detect_devices | () -> None | Auto-detect available devices |
poll | () -> None | Poll all devices |
| Property | Type | Description |
|---|---|---|
mouse_position | Tuple[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.
| Property | Type | Description |
|---|---|---|
path | str | Device path |
name | str | Device 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")
| Parameter | Type | Default | Description |
|---|---|---|---|
width | int | 240 | Display width |
height | int | 240 | Display height |
controller | str | "st7789" | Controller type |
rotation | int | 0 | Display rotation |
| Method | Signature | Description |
|---|---|---|
initialize | () -> None | Initialize display |
resize | (width, height) -> None | Resize display |
get_pixel_buffer | () -> array.array | Get back buffer |
flip | () -> None | Present back buffer |
capture_framebuffer | (path: str) -> None | Save framebuffer to PNG |
quit | () -> None | Clean up resources |
set_pixel | (x, y, color) -> None | Set single pixel |
| Property | Type | Description |
|---|---|---|
renderer | None | MCU uses pixel buffer, not renderer |
Additional Widgets
Window
Module: pyhmi.widgets.window
Top-level window container. Root widget for PyHML scenes.
| Property | Type | Default | Description |
|---|---|---|---|
title | str | "PyHMI Window" | Window title |
width | int | 320 | Window width |
height | int | 240 | Window height |
background_color | RGBA | (247,248,250,255) | Background color |
layout | Layout | None | None | Layout engine |
List
Module: pyhmi.widgets.list
Simple list container with selection support.
| Property | Type | Default | Description |
|---|---|---|---|
items | list | ["Item 1", ...] | List items |
selected_index | int | -1 | Selected item index |
font_size | int | 12 | Font size |
Signals: ValueChanged
ListView
Module: pyhmi.widgets.listview
Scrollable list view with drag-to-scroll support.
| Property | Type | Default | Description |
|---|---|---|---|
items | list | ["Item 1", ...] | List items |
selected_index | int | -1 | Selected item index |
font_size | int | 12 | Font size |
Signals: ValueChanged
ScrollBar
Module: pyhmi.widgets.scrollbar
Scrollbar widget for scrollable content. Supports vertical and horizontal orientation.
| Property | Type | Default | Description |
|---|---|---|---|
value | float | 0.0 | Current scroll position |
min_value | float | 0.0 | Minimum value |
max_value | float | 100.0 | Maximum value |
page_size | float | 20.0 | Visible page size |
orientation | str | "vertical" | "vertical" or "horizontal" |
Signals: ValueChanged
VideoDecoder
Module: pyhmi.widgets.video
Video decoder supporting MP4 and MJPEG formats via Pillow.
| Property | Type | Description |
|---|---|---|
source | str | Video file path or URL |
fps | float | Target frames per second |
frames | List[VideoFrame] | Decoded frames |
total_frames | int | Frame count |
duration | float | Duration in seconds |
is_loaded | bool | Successfully loaded |
error | str | None | Error message |
| Method | Signature | Description |
|---|---|---|
get_frame | (index: int) -> VideoFrame | None | Get frame by index |
VideoFrame
Module: pyhmi.widgets.video
A single decoded video frame.
| Property | Type | Description |
|---|---|---|
pixels | List[int] | Pixel data |
width | int | Frame width |
height | int | Frame 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:
main.py— Entry point with backend initscenes/— PyHML scene files (home, settings, about).vscode/tasks.json— VS Code tasks.vscode/launch.json— Debug configuration.vscode/settings.json— Interpreter settings.gitignore— Git ignore rules.gitattributes— Line ending enforcementrequirements.txt— Dependenciespyproject.toml— Project configurationREADME.md— Project documentation
Advanced mode questions:
- Target platform (linux, mcu, desktop)
- Display width
- Display height
- Backends (sdl2, framebuffer, spi_lcd)
- Input devices (keyboard, mouse, touch)
- Scene count
- Theme (dark, light, custom)
- Project description
- Include examples (y/n)