[< Back to Part 2](Part 2 - Events.ipynb) or Index
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 model can be child of another. In other words, widget A cannot have widget B listed twice in it's children list.
Widgets that can contain other widgets have a children
property. This property 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 (as seen below).
floatrange = widgets.FloatSliderWidget()
string = widgets.TextBoxWidget(value='hi')
container = widgets.ContainerWidget(children=[floatrange, 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)
intrange = widgets.IntSliderWidget()
container.children=[intrange]
Visibility¶
Sometimes it's necessary to hide/show widget views in place, without having to redisplay the widget views. The visibility
property of widgets can be used to hide/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.TextBoxWidget(description="First Name:")
last = widgets.TextBoxWidget(description="Last Name:")
student = widgets.CheckBoxWidget(description="Student:", value=False)
school_info = widgets.ContainerWidget(visible=False, children=[
widgets.TextBoxWidget(description="School:"),
widgets.IntTextWidget(description="Grade:", min=0, max=12)
])
pet = widgets.TextBoxWidget(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')
In [Part 4](Part 4 - Styles.ipynb) of this series, you will learn about widget styling.