在 ipywidgets 中使用动态数量的滑块
Using dynamic number of sliders with ipywidgets
我想使用 ipywidgets
和动态数量的滑块以交互方式调用一个函数。
我可以显示它。
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)
这会正确呈现三个由 n_alphas
定义的垂直滑块。
不幸的是,我无法将此 UI 与滑块的动态数量绑定到某些功能。
我尝试了以下变体,但没有任何效果:
out = widgets.interactive_output(print_alphas, alphas)
display(ui, out)
将 alphas
定义的滑块列表绑定到函数 print_alphas
需要什么?应该如何定义该函数本身?
我建议单独 monitoring 从该监视器功能中访问所有 alpha 的滑块:
# 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)
我想使用 ipywidgets
和动态数量的滑块以交互方式调用一个函数。
我可以显示它。
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)
这会正确呈现三个由 n_alphas
定义的垂直滑块。
不幸的是,我无法将此 UI 与滑块的动态数量绑定到某些功能。 我尝试了以下变体,但没有任何效果:
out = widgets.interactive_output(print_alphas, alphas)
display(ui, out)
将 alphas
定义的滑块列表绑定到函数 print_alphas
需要什么?应该如何定义该函数本身?
我建议单独 monitoring 从该监视器功能中访问所有 alpha 的滑块:
# 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)