0

I'm attempting to create a class to easily create and generate jupyter widgets for dashboards in my notebooks. This class so far has an add_row and display method. I'm having trouble finding a way to easily pass parameters to the widget object as different widgets require different things (instead of using a 100 if statements for each widget). It works fine for TextBox at the moment but I want to extend it to get it to work with all widgets.

Here's a sample of the add_row method:

# types: Type of widgets ex: ['Text', 'Text', 'Text']
# labels: Label names ['A', 'B', 'C']
# values: Default values ['', '', '']

for i in range(len(labels)):
    w = getattr(widgets, types[i])

    row.append(w(description=labels[i], value=values[i]))

self.rows.append(widgets.HBox(row))
Supez38
  • 329
  • 1
  • 3
  • 16

1 Answers1

0

I've worked up a simple class for this, you need to pass a list of dictionaries to the add_rows method, where each dict has the widget class you want to create, plus any extra kwargs which you need to create the widget. It should work for any widget type as long as you provide the correct kwargs.

import ipywidgets as ipyw

class WidgetAppender:

    def __init__(self):
        self.box = ipyw.VBox()
        display(self.box)

    def add_rows(self, list_of_dicts):
        for input_dict in list_of_dicts:
            widget_class = input_dict.pop('class')
            widget = widget_class(**input_dict)
            self.box.children = self.box.children + (widget,)

wa = WidgetAppender()
display(wa)

wa.add_rows(
[{'class': ipyw.Text, 'description':'Hi'},
 {'class': ipyw.Checkbox, 'value': False}]
)
ac24
  • 5,325
  • 1
  • 16
  • 31