Your first window

This page builds a counter: a number and two buttons. It has every part a juno.ui program needs.

A counter on iPhone A counter on iPhone
"""A counter: a number with an Add button and a Reset button."""

from dataclasses import dataclass

from juno import ui


@dataclass
class State:
    count: int = 0


state = State()


def add():
    state.count += 1


def reset():
    state.count = 0


def body(s):
    return ui.VStack(
        ui.Text(str(s.count), font="large_title", weight="bold"),
        ui.HStack(
            ui.Button("Reset", on_press=reset, style="bordered", disabled=s.count == 0),
            ui.Button("Add", on_press=add, style="filled"),
            spacing=12),
        spacing=16, padding=20, width="fill", max_width=680)


if __name__ == "__main__":
    ui.run(body, state, title="Counter")

Step by step

  1. The state. State is a dataclass with one field, count. Any Python object works; a dataclass keeps it tidy.

  2. The callbacks. add and reset change the state. Give a button the function itself, on_press=add, not the result of calling it, add().

  3. The body. body(s) returns one VStack: the number on top, and a row of two buttons under it. A number goes through str() before it reaches ui.Text. Reset is disabled with disabled= while the count is zero.

  4. Running. ui.run(body, state, title="Counter") opens the window with that title. Putting it under if __name__ == "__main__": lets another file import your functions without opening the window.

Closing the window

The Close button in the window’s corner ends ui.run normally, and the lines after it run. With a hardware keyboard, Command-I or Control-C stops the script instead, and then ui.run raises KeyboardInterrupt.

Your own code can close the window with ui.close(), for example from a Done button.

What stays out of body

Juno calls body often, and only to describe the screen. Don’t show dialogs, start timers, read or write files, or change the state there. Do that work in callbacks, or in on_appear, which runs once when the window opens:

ui.run(body, state, title="Counter", on_appear=load)

In a notebook

A notebook cell can call ui.run too. The cell keeps running while the window is open and finishes when the window closes.

Next

  • List shows rows from your data.

  • Native UI explains how state, body and callbacks fit together.