yugui reference¶
Generated from the docstrings by scripts/gen_reference.py: edit those, not this file. Every name here is available as yugui.<name>, usually imported as import yugui as ui.
Apps¶
App¶
Base class for a yugui application (the Elm architecture).
Subclasses implement init, update and view. title, theme and subscription are optional, and each may be a plain value or a method of the model:
class Clock(ui.App[Model]):
title = "Clock" # constant
def theme(self, model): # depends on the model
return "Dark" if model.dark else "Light"
Subclassing is not required: any object with init, update and view will do. All methods run on the main thread, one at a time, so the model needs no locking.
Program¶
An app as the native runtime sees it: seven methods of the model.
init is the app's own bound method. update wraps the app's to return (model or None, tasks) (see yugui.tasks). While view and windows run, every ui.set path is checked against the model (see yugui.setters), unless the app sets check_setters = False or Python runs with -O; then view is the app's own bound method. The optional title, theme, subscription and windows are turned into methods, with their defaults filled in; windows returns a list.
run¶
Open the app's window and run until it is closed.
Must be called from the main thread. Ctrl-C quits.
Widgets¶
column¶
column(*content: Child, spacing: float | None = None, padding: Padding | None = None, width: Length | None = None, height: Length | None = None, max_width: float | None = None, align_x: Align | None = None, keys: Iterable[Hashable] | None = None) -> Node
Lay children out top to bottom.
With keys (one hashable per child, after None children are dropped), widget state such as focus follows each child by key rather than by position, so inserting or removing a child above a focused text input doesn't move the focus.
row¶
row(*content: Child, spacing: float | None = None, padding: Padding | None = None, width: Length | None = None, height: Length | None = None, align_y: Align | None = None, wrap: bool = False) -> Node
Lay children out left to right; wrap=True flows onto new lines.
container¶
container(content: Child, *, padding: Padding | None = None, width: Length | None = None, height: Length | None = None, max_width: float | None = None, align_x: Align | None = None, align_y: Align | None = None, style: ContainerStyle | None = None, background: Color | None = None) -> Node
Wrap one child to pad, size, align or decorate it.
background paints over the style's background, if any.
center¶
A container that fills its parent and centers its child.
scrollable¶
scrollable(content: Child, *, id: str | None = None, width: Length | None = None, height: Length | None = None, direction: Literal['vertical', 'horizontal', 'both'] | None = None, on_scroll: Handler[Viewport] = None, anchor: Literal['start', 'end'] | None = None, scrollbar_width: float | None = None, scrollbar_margin: float | None = None, scroller_width: float | None = None) -> Node
Scroll one child that may be larger than the space given.
on_scroll receives a yugui.events.Viewport when the scroll position or the visible size changes, including once after the first frame. anchor="end" starts at the bottom (or the right) and keeps that end in view as the content grows, as a log or a chat does. The other options size the scrollbar track, its margin and its handle.
grid¶
grid(*content: Child, columns: int | None = None, spacing: float | None = None, fluid: float | None = None, height: Length | None = None, aspect_ratio: float | None = None) -> Node
Lay children out in equal-width cells, columns per row.
With fluid=max_width instead, the number of columns follows the available width, with cells at most max_width wide. Cells are square by default; aspect_ratio (width / height) changes their shape, and height="shrink" sizes each row to its content (a number or "fill" shares that height between the rows). For label and field pairs, see form.
space¶
Empty space; space(width="fill") pushes siblings apart.
rule¶
rule(*, direction: Literal['horizontal', 'vertical'] | None = None, thickness: float | None = None) -> Node
A separating line.
text¶
text(content: object, *, size: float | None = None, color: Color | None = None, width: Length | None = None, align_x: Align | None = None, monospace: bool = False) -> Node
A piece of text; content goes through str().
button¶
button(content: Child, *, on_press: Any = None, style: ButtonStyle | None = None, padding: Padding | None = None, width: Length | None = None, height: Length | None = None) -> Node
A button; disabled when on_press is None.
text_input¶
text_input(value: str, *, id: str | None = None, on_input: Handler[str] = None, on_submit: Any = None, placeholder: str | None = None, secure: bool = False, invalid: bool = False, size: float | None = None, padding: Padding | None = None, width: Length | None = None) -> Node
A one-line text field; read-only when on_input is None.
invalid=True draws it in the theme's danger colour. id names it for tasks such as yugui.focus.
checkbox¶
checkbox(checked: bool, *, label: str | None = None, on_toggle: Handler[bool] = None, width: Length | None = None, style: Literal['primary', 'secondary', 'success', 'danger'] | None = None) -> Node
A check box; on_toggle receives the new state. Without on_toggle it is disabled.
toggler¶
toggler(checked: bool, *, label: str | None = None, on_toggle: Handler[bool] = None, width: Length | None = None) -> Node
A switch; on_toggle receives the new state.
slider¶
slider(value: float, *, range: tuple[float, float] = (0.0, 1.0), on_change: Handler[float] = None, step: float | None = None, shift_step: float | None = None, default: float | None = None, width: Length | None = None) -> Node
A horizontal slider; on_change receives the new value.
shift_step is the step while shift is held; default is the value a ctrl-click (cmd-click on macOS) resets to.
vertical_slider¶
vertical_slider(value: float, *, range: tuple[float, float] = (0.0, 1.0), on_change: Handler[float] = None, step: float | None = None, shift_step: float | None = None, default: float | None = None, height: Length | None = None) -> Node
A vertical slider; like slider, upright.
radio¶
radio(label: str, value: T, selected: T | None, *, on_select: Handler[T] = None, size: float | None = None, spacing: float | None = None, text_size: float | None = None, width: Length | None = None) -> Node
One choice among several: checked when value == selected.
Give every radio of a group the same selected and on_select; on_select receives this radio's value:
ui.column([
ui.radio(str(c), c, model.color, on_select=ui.set("color"))
for c in Color
])
progress_bar¶
progress_bar(value: float, *, range: tuple[float, float] = (0.0, 1.0), length: Length | None = None, girth: Length | None = None, vertical: bool = False) -> Node
A bar filled in proportion to value within range; with vertical=True it fills from the bottom up.
pick_list¶
pick_list(options: Iterable[T], selected: T | None, *, on_select: Handler[T] = None, placeholder: str | None = None, width: Length | None = None) -> Node
A drop-down list; options are shown with str().
on_select receives the chosen option itself.
combo_box¶
combo_box(options: Iterable[T], selected: T | None, *, id: str, on_select: Handler[T] = None, on_input: Handler[str] = None, on_hover: Handler[T] = None, on_close: Any = None, placeholder: str | None = None, width: Length | None = None) -> Node
A text field whose list of options narrows down as the user types; options are shown with str().
on_select receives the chosen option itself, on_input the text typed, on_hover the option under the pointer or the arrow keys while the list is open; on_close is sent when the list closes. The text typed so far is kept under id between views.
text_editor¶
text_editor(value: str, *, id: str, on_change: Handler[str] = None, placeholder: str | None = None, monospace: bool = False, size: float | None = None, padding: Padding | None = None, width: float | None = None, height: Length | None = None) -> Node
A multi-line text field; read-only when on_change is None.
on_change receives the whole text after each edit; moving the cursor or selecting sends nothing. The cursor and selection are kept under id between views, along with the text last sent: a value other than that one (after an undo, say) replaces the text and puts the cursor back at the start. width is in pixels; by default the editor fills the width it is given.
image¶
image(source: str | PathLike[str] | bytes, *, width: Length | None = None, height: Length | None = None, content_fit: ContentFit | None = None, filter: Literal['linear', 'nearest'] | None = None) -> Node
A raster image (PNG, JPEG, GIF, …) from a file path or encoded bytes.
By default it keeps its aspect ratio and fits its bounds (content_fit="contain"). filter="nearest" scales it without smoothing, for pixel art.
svg¶
svg(source: str | PathLike[str] | bytes, *, width: Length | None = None, height: Length | None = None, content_fit: ContentFit | None = None) -> Node
A vector image from an SVG file path, or SVG text as bytes.
stack¶
Draw children on top of each other, the last one on top.
tooltip¶
tooltip(content: Child, tip: Child, *, position: Literal['top', 'bottom', 'left', 'right', 'follow_cursor'] = 'top', gap: float | None = None, padding: float | None = 4, delay: float | None = None, style: str | None = 'box') -> Node
Show tip next to content while the pointer is over it, after delay seconds. style names the tip's box, as for container.
explain¶
Draw the bounds of content and of every widget inside it, to see how the layout came out.
opaque¶
Keep pointer events from reaching the layers below content.
pin¶
Place content at (x, y) within the space given to the pin.
Use it in a stack for popups at a given position.
mouse_area¶
mouse_area(content: Child, *, on_press: Any = None, on_release: Any = None, on_right_press: Any = None, on_double_click: Any = None, on_enter: Any = None, on_exit: Any = None, on_move: Handler[MouseEvent] = None) -> Node
Send messages for pointer events over content.
shortcuts¶
Send a message when a key in keys is pressed while content is shown: {"Escape": "close", "cmd+s": "save"}.
Keys are named as in yugui.KeyEvent ("Enter", "ArrowUp", "F5", "s"), after modifiers among shift, ctrl, alt, logo and cmd (the platform's command key), which must all be held, and no others. content sees the keys first: a focused text input keeps what is typed into it. A key that matches goes no further, not even to yugui.on_key subscriptions.
canvas¶
canvas(shapes: Iterable[Node], *, width: Length | None = None, height: Length | None = None, background: Color | None = None, on_press: Handler[MouseEvent] = None, on_release: Handler[MouseEvent] = None, on_move: Handler[MouseEvent] = None, on_hover: Handler[Any] = None, pick: Literal['top', 'nearest'] | None = None, cursor: Literal['pointer', 'crosshair'] | None = None, viewbox: tuple[float, float, float, float] | None = None) -> Node
Draw shapes (circle, rect, line, path, label) in order, the last one on top.
Handlers receive a yugui.events.MouseEvent with coordinates relative to the canvas. Presses and releases inside the canvas are not seen by widgets below it.
With viewbox=(x, y, width, height), shapes are drawn in their own coordinates, and that rectangle is scaled to fit the canvas, centred and keeping its proportions (as an SVG viewBox). Line widths and text sizes scale with it, and mouse events are reported in the same coordinates. Use it for drawings that should grow with the window.
Shapes given a key can be hit: a press's MouseEvent.target is the key of the shape under the pointer, or None, and on_hover receives the key under the pointer (or None) whenever it changes, including when shapes move under a still pointer. Where keyed shapes overlap, pick="top" (the default) chooses the last drawn and pick="nearest" the one whose centre is nearest. cursor="pointer" shows a hand over keyed shapes, cursor="crosshair" crosshairs over the whole canvas.
circle¶
circle(x: float, y: float, radius: float, *, fill: Fill | None = None, stroke: Color | None = None, stroke_width: float | None = None, key: Hashable | None = None) -> Node
A circle shape. Without fill or stroke, it is outlined in the theme's text colour. A key makes it hittable (see canvas).
rect¶
rect(x: float, y: float, width: float, height: float, *, fill: Fill | None = None, stroke: Color | None = None, stroke_width: float | None = None, key: Hashable | None = None) -> Node
A rectangle shape, from its top-left corner.
line¶
line(x1: float, y1: float, x2: float, y2: float, *, stroke: Color | None = None, stroke_width: float | None = None, cap: Cap | None = None, key: Hashable | None = None) -> Node
A line segment shape. With a key, it is hit within 4 pixels. cap shapes its ends: "butt" (the default), "round" or "square".
path¶
path(commands: Iterable[PathCommand], *, fill: Fill | None = None, stroke: Color | None = None, stroke_width: float | None = None, cap: Cap | None = None) -> Node
A shape made of segments and curves, from commands such as:
("move", x, y) # start a new part here
("line", x, y) # a straight line to (x, y)
("quad", cx, cy, x, y) # a quadratic curve
("cubic", c1x, c1y, c2x, c2y, x, y) # a cubic Bézier curve
("arc", cx, cy, radius, start, end) # angles in radians,
# clockwise from the x axis
("close",) # back to the part's start
Like other shapes, it is filled and/or outlined, and outlined in the theme's text colour without either. Paths can't be hit (they take no key): work out what was clicked from the event's coordinates.
linear_gradient¶
linear_gradient(start: tuple[float, float], end: tuple[float, float], stops: Iterable[tuple[float, Color]]) -> Gradient
A gradient along the line from start to end (canvas coordinates), through (offset, colour) stops with offsets from 0 to 1. Use it as a canvas shape's fill.
label¶
label(content: object, x: float, y: float, *, size: float | None = None, color: Color | None = None, align_x: Literal['left', 'center', 'right'] | None = None, align_y: Literal['top', 'center', 'bottom'] | None = None, monospace: bool = False) -> Node
A text shape. (x, y) is its top-left corner, unless align_x and align_y say which point of the text it is.
Composite widgets¶
modal¶
modal(base: Child, dialog: Child, *, on_dismiss: Any = None, backdrop: Color | None = '#00000066') -> Node
Show dialog centred over base, which it dims and blocks.
Clicks inside the dialog stay there; a click on the backdrop, or Escape, sends on_dismiss, or nothing if it is None.
popup¶
Show content (a menu, say) at (x, y) over base.
A click anywhere outside it sends on_dismiss and goes no further, as with desktop menus: it doesn't also act on what is underneath. Escape sends on_dismiss too.
form¶
form(*rows: tuple[str, Child] | None, label_width: float = 100, spacing: float = 8, width: Length | None = None) -> Node
Label and field pairs, one per row, with the fields lined up.
None rows are skipped, so cond and ("Label:", field) works.
visible_range¶
visible_range(offset: float, extent: float, item_size: float, count: int, overscan: int = 0) -> range
The indexes of the items of size item_size that are visible between offset and offset + extent, plus overscan on each side, clipped to range(count).
virtual_list¶
virtual_list(count: int, *, row_height: float, render: Callable[[int], Child], viewport: Viewport | None, on_scroll: Handler[Viewport], overscan: int = 4, id: str | None = None, width: Length | None = 'fill', height: Length | None = 'fill', content_width: float | None = None) -> Node
A scrolling list of count rows that builds only the visible ones.
Every row is given exactly row_height pixels. The scroll position lives in the model: on_scroll receives a yugui.events.Viewport to store (on_scroll=ui.set("viewport")), and viewport gives it back. Rows are keyed by index, so a focused row keeps its focus while the list scrolls.
With content_width, the list also scrolls horizontally, and rows may cut their own columns with visible_range and viewport.x.
virtual_grid¶
virtual_grid(rows: int, columns: int, *, cell: Callable[[int, int], Child], cell_size: tuple[float, float], viewport: Viewport | None, on_scroll: Handler[Viewport], column_header: Callable[[int], Child] | None = None, row_header: Callable[[int], Child] | None = None, row_header_width: float = 40, overscan: int = 2, id: str | None = None, width: Length | None = 'fill', height: Length | None = 'fill') -> Node
A grid of rows × columns cells, scrolling both ways, that builds only the cells in view.
cell(row, column) builds a cell; every cell is given exactly cell_size (width, height). column_header(column) adds a header row on top, and row_header(row) a header column row_header_width wide on the left; both scroll with the cells. As with virtual_list, the scroll position lives in the model: on_scroll receives a yugui.events.Viewport to store and viewport gives it back.
window¶
window(key: Hashable, content: Child, *, title: str | None = None, size: tuple[float, float] | None = None, on_close: Any = None) -> Node
A secondary window, returned from App.windows(model).
The window is open while windows() returns it (matched by key) and closes when it stops doing so. Its close button sends on_close and doesn't close it by itself: the model decides.
Messages from widgets¶
Set¶
The message sent by a set handler.
Setter¶
A handler that turns a widget's value into Set(path, value).
set¶
A handler that sends Set(path, value) with the widget's value.
Events¶
MouseEvent¶
class MouseEvent(x: float, y: float, button: Literal['left', 'right', 'middle'] | None = None, target: Hashable | None = None)
A pointer event, in pixels relative to the widget's top-left corner.
button is "left", "right" or "middle" for presses and releases, and None for moves. On a canvas, target is the key of the shape under the pointer, if any (see yugui.canvas).
Viewport¶
class Viewport(x: float, y: float, width: float, height: float, content_width: float, content_height: float)
What a scrollable shows: its scroll offsets and visible size, and the size of its whole content, in pixels.
Modifiers¶
The modifier keys held during a key event.
KeyEvent¶
class KeyEvent(key: str, modifiers: Modifiers = Modifiers(shift=False, ctrl=False, alt=False, logo=False), text: str | None = None, kind: Literal['press', 'release'] = 'press', repeat: bool = False, modified_key: str | None = None)
A key pressed or released, from yugui.on_key.
key names the key as iced does: a named key by name ("Enter", "Escape", "ArrowUp", "F5", "Space"), any other key by the character it types without shift ("a", "1"). modified_key is the key with shift applied ("A", "!"), and text the text the press types, if any.
WindowEvent¶
class WindowEvent(kind: str, window: Hashable | None = None, x: float | None = None, y: float | None = None, width: float | None = None, height: float | None = None, path: Path | None = None)
Something that happened to a window, from yugui.on_window.
kind is "resized" (with width and height), "moved" (with x and y), "focused", "unfocused", "file_hovered" or "file_dropped" (with path), or "files_hovered_left". window is the key of a secondary window, or None for the main one.
Subscriptions¶
every¶
Send message every seconds.
on_key¶
Call handler with a yugui.KeyEvent for each key pressed (or released, with release=True) and send what it returns; None sends nothing. Without a handler, the events are sent as is.
Only keys no widget took are seen: while a text input has the focus, the keys typed into it don't reach handler. :
def subscription(self, model):
yield ui.on_key(shortcut)
def shortcut(event):
if event.key == "z" and event.modifiers.command:
return "undo"
return None
on_window¶
Call handler with a yugui.WindowEvent when a window is resized, moved, focused or unfocused, or when files are dragged onto it, and send what it returns; None sends nothing. Without a handler, the events are sent as is.
Tasks¶
Task¶
A request to the runtime, such as moving the keyboard focus.
focus¶
Give the keyboard focus to the widget with this id.
focus_next¶
Move the keyboard focus to the next focusable widget, as Tab does in most toolkits (iced leaves Tab to the app: see yugui.on_key).
focus_previous¶
Move the keyboard focus to the previous focusable widget.
select_all¶
Select all the text of the text input with this id.
exit¶
Close all windows and return from yugui.run.
alert¶
alert(text: str, *, title: str | None = None, level: Literal['info', 'warning', 'error'] = 'info', on_close: Any = None) -> Task
Show a message box with an OK button; send on_close once closed.
confirm¶
confirm(text: str, *, title: str | None = None, level: Literal['info', 'warning', 'error'] = 'info', on_result: Callable[[bool], Any]) -> Task
Ask a yes/no question; on_result receives True for yes.
open_file¶
open_file(*, on_result: Callable[[Path | None], Any], title: str | None = None, filters: Filters | None = None, directory: str | Path | None = None) -> Task
Ask for a file to open; on_result receives its path, or None if the user cancelled. filters maps a name to extensions: {"CSV": ["csv"]}.
save_file¶
save_file(*, on_result: Callable[[Path | None], Any], title: str | None = None, filters: Filters | None = None, directory: str | Path | None = None, file_name: str | None = None) -> Task
Ask where to save a file; on_result receives the path, or None if the user cancelled.
perform¶
Run fn(*args) on a thread of its own, so the window stays responsive, then send then(result), or the result itself without then. If fn raises, send catch(exception); without catch the exception is printed and nothing is sent. A None result sends nothing.
fn runs outside update: it must not touch the model. :
return replace(model, loading=True), ui.perform(
fetch, url, then=Fetched, catch=Failed
)
scroll_to¶
Scroll the scrollable with this id to (x, y) pixels from its start; None leaves that axis where it is.
snap_to¶
Scroll the scrollable with this id to a relative position: 0 is the start, 1 the end; None leaves that axis alone.
Undo history¶
History¶
class History(present: T, past: tuple[T, ...] = (), future: tuple[T, ...] = (), limit: int | None = None)
A value with its past and its undone future. Immutable: every method returns a new history.
View nodes¶
Node¶
One widget or subscription: a kind, its properties and its children.
Nodes are inert data. The widget functions in yugui.widgets build them; nothing happens until yugui.run renders the tree.
Constants and types¶
THEMES¶
The names theme accepts: Light, Dark, Dracula, Nord, Solarized Light, Solarized Dark, Gruvbox Light, Gruvbox Dark, Catppuccin Latte, Catppuccin Frappé, Catppuccin Macchiato, Catppuccin Mocha, Tokyo Night, Tokyo Night Storm, Tokyo Night Light, Kanagawa Wave, Kanagawa Dragon, Kanagawa Lotus, Moonfly, Nightfly, Oxocarbon, Ferra.
The types used in the signatures above:
Child = Node | str | Sequence[Child] | None | bool
Length = float | Literal["fill", "shrink"] | tuple[Literal["fill"], int]
Padding = float | tuple[float, float] | tuple[float, float, float, float]
Align = Literal["start", "center", "end"]
Color = str | tuple[float, float, float] | tuple[float, float, float, float]
Cap = Literal["butt", "round", "square"]
PathCommand = (
tuple[Literal["move", "line"], float, float]
| tuple[Literal["quad"], float, float, float, float]
| tuple[Literal["cubic"], float, float, float, float, float, float]
| tuple[Literal["arc"], float, float, float, float, float]
| tuple[Literal["close"]]
)
Fill = Color | Gradient
Handler = Callable[[T], Any] | Any
ButtonStyle = Literal[
"primary",
"secondary",
"success",
"warning",
"danger",
"text",
"subtle",
"background",
]
ContainerStyle = Literal[
"box", "bordered", "dark", "primary", "secondary", "success", "danger", "warning"
]
ContentFit = Literal["contain", "cover", "fill", "none", "scale_down"]
Testing¶
In yugui.testing.
Driver¶
Driver.view¶
The main window's tree, or the content of window window.
Driver.send¶
Feed messages to update, as if widgets had sent them, then let frames be drawn until the app settles.
Driver.run¶
Apply raw actions (see _native.Session.run) to the current view, send the resulting messages to update and return them, followed by those of on_key subscriptions for keys no widget took.
Driver.click¶
Click the widget that shows text, such as a button label.
Driver.click_at¶
Driver.click_at(self, x: float, y: float, button: Button = 'left', *, window: Any = None) -> list[Any]
Driver.press_at¶
Driver.press_at(self, x: float, y: float, button: Button = 'left', *, window: Any = None) -> list[Any]
Press a mouse button at (x, y) without releasing it: with move_to and release_at, a drag.
Driver.release_at¶
Driver.release_at(self, x: float, y: float, button: Button = 'left', *, window: Any = None) -> list[Any]
Release a mouse button at (x, y).
Driver.double_click_at¶
Driver.move_to¶
Move the pointer; it stays there for the following calls.
Driver.scroll¶
Turn the mouse wheel over (x, y) to scroll content by (dx, dy) pixels (positive: towards the end).
Driver.type¶
Type text into the focused widget, one character at a time, with update and view in between as in a running app.
Driver.key¶
Press and release a key: a named key ("Enter", "Escape", "ArrowUp", "F5"…) or a character ("a"), with modifiers such as "ctrl+shift" ("cmd" is the platform's command key).
Driver.type_at¶
Click at a position (to focus a text input), then type text.
Driver.close¶
Press a secondary window's close button: send its on_close.
Driver.answer¶
Answer a dialog task (alert, confirm, open_file, save_file) as the user would, and send the resulting message.
value is True/False for a confirm, a path or None (cancelled) for a file dialog, and ignored for an alert.
Driver.complete¶
Run a pending yugui.perform task (the oldest one if task is None) and send its result, as when its thread ends. An exception without catch is raised here.
Driver.snapshot¶
Render a window as it stands now (scrolled, focused, hovered) to a PNG at path and return the path. theme defaults to the app's.