Skip to content

Tutorial: your first app

This tutorial builds two small apps, a counter and a to-do list, and then shows what else an app can do: lay out its widgets, react to timers and keys, run work in the background, and be tested. It assumes you know Python, including dataclasses and the match statement, and that you have installed yugui.

The idea

A yugui app has no widget objects that you create and then change. Instead, it has three parts:

  • a model, a Python value that holds the app's whole state;
  • update, a function that takes the model and a message, and returns the next model. A message says what happened: "the user pressed Add", "the text is now Buy milk";
  • view, a function that takes the model and returns the widgets that show it. Widgets send messages when the user acts on them.

yugui runs the loop: it shows view(model), waits for a message, calls update, and shows the view of the new model. This is called the Elm architecture, after the language that made it popular.

A counter

An app is a subclass of ui.App, with one method for each part, plus init for the first model. Here the model is a number:

import yugui as ui


class Counter(ui.App[int]):
    def init(self):
        return 0

    def update(self, count, message):
        match message:
            case "inc":
                return count + 1
            case "dec":
                return count - 1

    def view(self, count):
        return ui.column(
            ui.button("+", on_press="inc"),
            ui.text(count, size=40),
            ui.button("-", on_press="dec"),
            spacing=10,
            padding=20,
            align_x="center",
        )

Save it as counter.py, with this at the end to open the window, and run it with uv run python counter.py:

if __name__ == "__main__":
    ui.run(Counter())

ui.App[int] says that the model is an int; type checkers use it, yugui doesn't. A button's on_press is the message it sends when pressed, and a message can be any Python value: here, a string. ui.column stacks its children from top to bottom, 10 pixels apart, with 20 pixels of padding around them, centred.

Click through a session to see the loop at work:

view builds the whole view again after each message. That sounds wasteful, but views of hundreds of widgets take about a millisecond, and it means the window can never show something that disagrees with the model.

When update returns None, the model is kept. Here that happens for any message the match doesn't handle.

A to-do list

Real models have several fields. The usual way to write them is a frozen dataclass, updated with dataclasses.replace, which returns a copy with some fields changed. Here is a to-do list: a text input for the next item, and the items so far, each with a checkbox.

from dataclasses import dataclass, replace
from functools import partial


@dataclass(frozen=True)
class Item:
    text: str
    done: bool = False


@dataclass(frozen=True)
class Model:
    draft: str = ""
    items: tuple[Item, ...] = ()


@dataclass(frozen=True)
class Toggle:
    index: int
    done: bool


class Todo(ui.App[Model]):
    title = "To do"

    def init(self):
        return Model()

    def update(self, model, message):
        match message:
            case ui.Set():
                return message.apply(model)
            case "add" if model.draft.strip():
                item = Item(model.draft.strip())
                return replace(model, draft="", items=(*model.items, item))
            case Toggle(index, done):
                items = list(model.items)
                items[index] = replace(items[index], done=done)
                return replace(model, items=tuple(items))

    def view(self, model):
        ready = bool(model.draft.strip())
        return ui.column(
            ui.row(
                ui.text_input(
                    model.draft,
                    placeholder="What needs doing?",
                    on_input=ui.set("draft"),
                    on_submit="add",
                    width="fill",
                ),
                ui.button("Add", on_press="add" if ready else None),
                spacing=8,
            ),
            [
                ui.checkbox(item.done, label=item.text, on_toggle=partial(Toggle, i))
                for i, item in enumerate(model.items)
            ],
            spacing=8,
            padding=16,
        )

title sets the window's title. Here is the app in use:

Widgets send three kinds of messages:

  • Plain values. on_press="add" and on_submit="add" (Enter in the input) send the string "add".
  • Handler results. A widget that produces a value (an input's text, a checkbox's new state, a slider's position) calls its handler with the value and sends the result. partial(Toggle, i) turns the new state True into Toggle(i, True). A dataclass with one field is a handler as it is: on_input=Rename sends Rename("new text").
  • Setters. Often a widget edits one field and nothing else needs to happen. ui.set("draft") sends ui.Set("draft", text), and message.apply(model) returns a copy of the model with the field set, so there's no message class to write. Paths can be dotted, as in ui.set("address.city"). yugui checks them against the model when the view is built, so a typo fails at once instead of at the first keystroke.

A few more things the view shows:

  • Disabling. A button without on_press is disabled, so on_press="add" if ready else None disables Add while the draft is empty. The same goes for the on_... arguments of other widgets.
  • Lists of children. A list of widgets can stand where one widget is expected, as the checkboxes do here.
  • Optional children. None and False children are left out, so condition and ui.text("...") shows a widget only when the condition holds.

Frozen models make undo easy (keep the old ones) and bugs rare, but they aren't required. A mutable model works too: change it in place in update and return nothing. That can read better for large, deeply nested state.

Layout

ui.column and ui.row stack their children, ui.container wraps one child to pad, align or style it, and ui.scrollable scrolls one. ui.center(child) fills the space it's given and centres the child in it.

  • Sizes (width, height) are a number of pixels, "fill" to take the space left, or "shrink" to take only what the content needs.
  • spacing is the gap between children.
  • padding is the space inside the edges: one number for all four, (vertical, horizontal), or (top, right, bottom, left).

When a layout surprises you, wrap it in ui.explain(...), which outlines the bounds of every widget inside. The API reference lists every widget and its options.

Messages from outside the view: subscriptions

Not every message comes from a widget. A stopwatch needs a tick every tenth of a second, and an editor may want Cmd-Z wherever the focus is. An app gets these from subscription(model), which returns the event sources to listen to. yugui calls it again after each update, so the sources can depend on the model. In a stopwatch, for instance:

    def subscription(self, model):
        if model.running:
            yield ui.every(0.1, "tick")
        yield ui.on_key(undo_key)


def undo_key(event):
    """Cmd-Z on macOS, Ctrl-Z elsewhere."""
    return "undo" if event.key == "z" and event.modifiers.command else None

ui.every(seconds, message) sends the message at that interval, only while the model says the stopwatch runs. ui.on_key(handler) calls the handler with each key press, and sends what it returns. A handler that returns None sends nothing. on_key only sees the keys that no widget took: a focused text input keeps the characters typed into it.

Asking for things: tasks

Some messages call for an action rather than a new model: move the focus to an input, scroll a list to the end, open a file dialog, quit, or download something without freezing the window. update asks for these by returning a task with the model, as (model, task), or a task alone to keep the model. In an app that downloads a file, for instance:

            case "fetch":
                task = ui.perform(download, url, then=Downloaded, catch=Failed)
                return replace(model, loading=True), task

ui.perform calls download(url) on a thread of its own, so the window stays responsive, then sends Downloaded(result), or Failed(exception) if it raised. Other tasks move the focus (ui.focus(id), ui.focus_next()), scroll (ui.scroll_to, ui.snap_to), open dialogs (ui.alert, ui.confirm, ui.open_file, ui.save_file) or quit (ui.exit()).

Testing without a window

yugui.testing.Driver runs an app as a window would, but without opening one: iced lays the view out and finds what a click lands on, and the resulting messages go through your update. A driver remembers what a window does between steps (the focus, scroll positions, the pointer), so a test reads as a sequence of user actions:

from yugui.testing import Driver

d = Driver(Todo())
d.send(ui.Set("draft", "Buy milk"))
d.click("Add")
assert d.model.items == (Item("Buy milk"),)
assert d.model.draft == ""
d.send(Toggle(0, True))
assert d.model.items[0].done

d.click("Add") clicks the widget that shows "Add", and d.send(message) sends a message as if a widget had. d.type(text) types into the focused widget, d.key("Enter") presses a key, d.click_at(x, y) clicks at a position, and d.snapshot("todo.png") saves the view as a PNG. Tests run in milliseconds and need no display, so they work in CI. Testing apps covers the rest.

Where next