Py.Cafe

johnarban/

Thin Wrapper for rv.Btn to make a Button Toggle

Interactive Button Toggle Example

DocsPricing
  • app.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# check out https://solara.dev/ for documentation
# or https://github.com/widgetti/solara/
# And check out https://py.cafe/maartenbreddels for more examples
import solara
from solara.alias import rv
# reactive variables will trigger a component rerender
# when changed.
# When you change the default (now 0), hit the embedded browser
# refresh button to reset the state
clicks = solara.reactive(0)

@solara.component
def ButtonSwitch(
    value: solara.Reactive[bool] | bool, 
    *args, 
    on_value = None, 
    label="",
    **kwargs
    ):
    """
    A thin wrapper for rv.Btn that toggles a boolean value
    """

    value = solara.use_reactive(value, on_change=on_value)
    
    if label != '':
        kwargs["children"] =  kwargs.get("children",[]) + [solara.Text(label)]
    
    
    btn = rv.Btn(
        *args, 
        **kwargs)
    def _on_value_changed(*args):
        value.set(not value.value)
    
    solara.v.use_event(btn, "click", _on_value_changed)
    btn



@solara.component
def Page():
    print("The component render function gets called")
    is_button_green = solara.use_reactive(False)
    # change this code, and see the output refresh
    @solara.lab.computed
    def color():
        return 'green' if is_button_green.value else 'red'
    

    def increment():
        clicks.value += 1
        print("clicks", clicks)  # noqa

    solara.Button(label=f"Clicked: {clicks}", on_click=increment, color=color.value)

    with ButtonSwitch(
                value = False,
                on_value = is_button_green.set,
                color="green"
    ):
     solara.Text(f"Turn button {'red' if is_button_green.value else 'green'}")


# Solara also supports ipywidgets
# remove the Page component and assign an ipywidget to
# the page variable, e.g.
# page = mywidget