Search code examples
pythonipywidgets

Is there an easy way to loop through an array of checkbox variables in the display function?


I am working with Python's widgets library (see: import ipywidgets as widgets) and I am trying to simplify some code. Here is the main code block that I am using:

d = []
for a in X.columns:
    d.append(a) 
x = dict()
for i in range(len(d)):
    x[i] = widgets.Checkbox(options=d[i],description=d[i],disabled=False)
display(x[89])

What this means is that from variable x[0] through x[n] there is a corresponding checkbox prescribed that will show the checkbox and the corresponding variable associated with that x[n]. I want to make this more dynamic and instead of writing the below to see all the available checkboxes...

display(x[0],x[1],x[2],x[3],...,x[n])

I can do something more like this...

b = []
for a in range(len(d)):
    b.append("x[{}]".format(a))
display(b)

But this doesn't work. It prints out a list of a string that looks like this instead of the checkboxes with corresponding variable names.

['x[0]',
 'x[1]',
 'x[2]',
 'x[3]',...
 'x[n]']

I hope this makes sense. If anyone has any insight on how to address this, it would be greatly appreciated.


Solution

  • Your code is missing some key bits for me to help fully (e.g. you need to define the dataframe X, build a mocked copy from a dictionary or something).

    However, if you have a list of widgets, you need to place them in a container (like a widgets.HBox or widgets.VBox) and then you display the container

    import ipywidgets as widgets
    x = list()
    for i in range(5):
        widg = widgets.Checkbox(True,description=str(i),disabled=False)
        x.append(widg)
    box = widgets.VBox(tuple(x))
    display(box)