Search code examples
pythonjupyter-notebookipywidgets

Using dynamic number of sliders with ipywidgets


I want to call a function interactively using ipywidgets with a dynamic number of sliders. I am able to display it.

n_alphas = 3
alphas = [
    widgets.FloatSlider(min=-1, max=1, step=1e-3, description=f'$z_{i}$', orientation='vertical')
    for i in range(n_alphas)
]
ui = widgets.HBox(alphas)
display(ui)

This correctly renders three vertical sliders as defined by n_alphas.

three vertical sliders

Unfortunately I am not able to bind this UI with the dynamic number of sliders to some function. I tried variants of the following, but nothing worked:

out = widgets.interactive_output(print_alphas, alphas)
display(ui, out)

What is needed to bind the list of sliders defined by alphas to the function print_alphas and how should that function itself be defined?


Solution

  • I would suggest individually monitoring the sliders an accessing all alphas from within that monitor function:

    # monitor function, reporting both the changed value and all other values
    def handle_slider_change(change):
        values = [alpha.value for alpha in alphas]
        caption.value = (
            f'The slider {change.owner.description} has a value of {change.new}. '
            f'The values of all sliders are {values}'
        )
    
    # create sliders
    n_alphas = 3
    alphas = [
        widgets.FloatSlider(min=-1, max=1, step=1e-3, description=f'$z_{i}$', orientation='vertical')
        for i in range(n_alphas)
    ]
    # register slides
    for widget in alphas:
        widget.observe(handle_slider_change, names='value')
    
    # display ui
    ui = widgets.HBox(alphas)
    caption = widgets.Label(value='No change was made yet.')
    display(caption, ui)