ipywidgets: How to get array input?

Viewed 916

I need a widget that takes in an array as input, i.e. something like a hundred sliders (that I don't want to create manually).

How can I achieve this?

I thought the answer would be widgets.Box, but then I get the error Box(...) cannot be transformed to a widget.

2 Answers

Got it -- the trick is to use **kwargs. My code looks something like this.

seed = np.zeros(100)
kwargs = {'seed[{}]'.format(i) : 
          widgets.FloatSlider(
              min = -1.0, 
              max = 1.0, 
              step = 0.01, 
              value = seed[i]) 
          for i in range(100)}

@interact(**kwargs)
def Generate(**kwargs):
  return seed

A better solution will nonetheless be appreciated, because I don't know how to change the layout and stuff with this solution.

I think you need HBox or VBox, not just Box for a container.

import ipywidgets as widgets
from ipywidgets import interact
n = 10
seed = np.zeros(n)
sliders = list(widgets.FloatSlider(
              description = 'seed[{}]'.format(i),
              min = -1.0, 
              max = 1.0, 
              step = 0.01, 
              value = seed[i]) 
          for i in range(n))

widgets.VBox(children = sliders)
Related