##// END OF EJS Templates
first review pass on widget tests
first review pass on widget tests

File last commit:

r14724:796c0edb
r14797:85a0de32
Show More
Part 3 - Placement.ipynb
185 lines | 5.1 KiB | text/plain | TextLexer
/ examples / widgets / Part 3 - Placement.ipynb

[< Back to Part 2](Part 2 - Events.ipynb) or Index

In [1]:
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).

In [2]:
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.

In [3]:
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).

In [4]:
string = widgets.LatexWidget(value="Hello World!")
display(string) 
In [5]:
string.visible=False
In [6]:
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.

In [7]:
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.