Your first window¶
This page builds a counter: a number and two buttons. It has every part a juno.ui program needs.
"""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¶
The state.
Stateis a dataclass with one field,count. Any Python object works; a dataclass keeps it tidy.The callbacks.
addandresetchange the state. Give a button the function itself,on_press=add, not the result of calling it,add().The body.
body(s)returns oneVStack: the number on top, and a row of two buttons under it. A number goes throughstr()before it reachesui.Text. Reset is disabled withdisabled=while the count is zero.Running.
ui.run(body, state, title="Counter")opens the window with that title. Putting it underif __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.