##// END OF EJS Templates
Updated examples 3-6
Updated examples 3-6

File last commit:

r14720:48170033
r14720:48170033
Show More
Part 3 - Placement.ipynb
171 lines | 4.9 KiB | text/plain | TextLexer
/ examples / widgets / Part 3 - Placement.ipynb
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. With IPython widgets, the widgets are instances that live in the back-end (usally Python). There can be multiple views displayed in the front-end that represent one widget in the backend. Each view can be displayed at a different time. 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')