from IPython.html import widgets # Widget definitions
from IPython.display import display # Used to display widgets in the notebook
Parent/Child Relationships¶
To display widget A inside widget B, widget A must be a child of widget B. Only one instance of any particular widget can be child of another. In other words, widget A cannot have widget B listed twice in it's list of children.
Widgets that can contain other widgets have a children
attribute. This attribute can be set via a kwarg in the widget's constructor or after construction. Calling display on an object with children automatically displays those children, too.
float_range = widgets.FloatSliderWidget()
string = widgets.TextWidget(value='hi')
container = widgets.ContainerWidget(children=[float_range, string])
display(container) # Displays the `container` and all of it's children.
Children can also be added to parents after the parent has been displayed. The parent is responsible for rendering its children.
container = widgets.ContainerWidget()
display(container)
int_range = widgets.IntSliderWidget()
container.children=[int_range]
Visibility¶
Sometimes it is necessary to hide or show widgets in place, without having to redisplay the widget.
The visibility
property of widgets can be used to hide or show widgets that have already been displayed (as seen below).
string = widgets.LatexWidget(value="Hello World!")
display(string)
string.visible=False
string.visible=True
In the example below, a form is rendered, which conditionally displays widgets depending on the state of other widgets. Try toggling the student checkbox.
form = widgets.ContainerWidget()
first = widgets.TextWidget(description="First Name:")
last = widgets.TextWidget(description="Last Name:")
student = widgets.CheckboxWidget(description="Student:", value=False)
school_info = widgets.ContainerWidget(visible=False, children=[
widgets.TextWidget(description="School:"),
widgets.IntTextWidget(description="Grade:", min=0, max=12)
])
pet = widgets.TextWidget(description="Pet's Name:")
form.children = [first, last, student, school_info, pet]
display(form)
def on_student_toggle(name, value):
if value:
school_info.visible = True
else:
school_info.visible = False
student.on_trait_change(on_student_toggle, 'value')