Buttons and menus¶
Use a button for an action in your Python script’s native interface, such as adding a coffee to an order. For several choices that belong together, give them one menu button.
"""Choose a coffee and add it to the order."""
from dataclasses import dataclass
from juno import ui
@dataclass
class State:
drink: str = "Espresso"
count: int = 0
last: str = ""
state = State()
def choose(drink):
state.drink = drink
def add():
state.count += 1
state.last = state.drink
def body(s):
menu = ui.Menu(
ui.MenuItem("Espresso", lambda: choose("Espresso"), checked=s.drink == "Espresso"),
ui.MenuItem("Latte", lambda: choose("Latte"), checked=s.drink == "Latte"))
return ui.VStack(
ui.Text("Coffee order", font="title2", weight="bold"),
ui.Button(s.drink, menu=menu, symbol="cup.and.saucer", style="bordered"),
ui.Button("Add to order", on_press=add, style="filled"),
ui.Text(f"{s.count} ordered · Latest: {s.last}" if s.count else "No drinks yet"),
alignment="leading", spacing=12, padding=20)
if __name__ == "__main__":
ui.run(body, state, title="Coffee")
Do one thing with a button¶
Pass the function to on_press without parentheses. Tapping Add to order calls add() and puts the chosen drink in the order summary.
Put choices in a menu¶
Give the other button a menu with one MenuItem per drink. Tapping its title opens the menu, and choosing an item calls that item’s function with no arguments. Set checked from the current choice so the checkmark follows it. In the example, choosing Latte changes the button title before you add the drink.
For actions on just one row, see List.
Parameters¶
Parameter |
Default |
Meaning |
|---|---|---|
|
Required |
Button label; may be empty when symbol is given. |
|
|
Synchronous function accepting no arguments; omit it when menu is given. |
|
|
Optional SF Symbol name shown before the title. |
|
|
|
|
|
|
|
|
Optional colour; defaults to the window tint. |
|
|
|
|
|
Optional Menu shown when the button is tapped. |
|
|
Boolean; show an activity indicator and block activation. |
Common keywords |
|
Parameter |
Default |
Meaning |
|---|---|---|
|
Variadic |
One to 24 MenuItem or Menu descriptions. |
|
|
Optional header. |
|
|
Optional persistent sibling key. |
Parameter |
Default |
Meaning |
|---|---|---|
|
Required |
Nonempty item label. |
|
Required |
Synchronous function accepting no arguments. |
|
|
Optional SF Symbol name shown beside the title. |
|
|
Show a checkmark. |
|
|
Draw the item in red. |
|
|
Show the item dimmed; it cannot be chosen. |
|
|
Optional persistent sibling key. |
Seen in¶
Run Tasks from Home’s Native UI section and open its Sort By menu to try a menu in a larger project.