from IPython.html import widgets # Widget definitions
from IPython.display import display # Used to display widgets in the notebook
Traitlet Events¶
The widget properties are IPython traitlets. Traitlets are eventful. To handle property value changes, the on_trait_change
method of the widget can be used to register an event handling callback. The doc string for on_trait_change
can be seen below. Both the name
and remove
properties are optional.
print(widgets.Widget.on_trait_change.__doc__)
Mentioned in the doc string, the callback registered can have 4 possible signatures:
- callback()
- callback(trait_name)
- callback(trait_name, new_value)
- callback(trait_name, old_value, new_value)
An example of how to output an IntRangeWiget's value as it is changed can be seen below.
intrange = widgets.IntRangeWidget()
display(intrange)
def on_value_change(name, value):
print value
intrange.on_trait_change(on_value_change, 'value')
Specialized Events¶
Button On Click Event¶
The ButtonWidget
is a special widget, like the ContainerWidget
and MulticontainerWidget
, that isn't used to represent a data type. Instead the button widget is used to handle mouse clicks. The on_click
method of the ButtonWidget
can be used to register a click even handler. The doc string of the on_click
can be seen below.
print(widgets.ButtonWidget.on_click.__doc__)
Button clicks are tracked by the clicks
property of the button widget. By using the on_click
method and the clicks
property, a button that outputs how many times it has been clicked is shown below.
button = widgets.ButtonWidget(description="Click Me!")
display(button)
def on_button_clicked(sender):
print("Button clicked %d times." % sender.clicks)
button.on_click(on_button_clicked)
Event handlers can also be used to create widgets. In the example below, clicking a button spawns another button with a description equal to how many times the parent button had been clicked at the time.
def show_button(sender=None):
button = widgets.ButtonWidget()
button.description = "%d" % (sender.clicks if sender is not None else 0)
display(button)
button.on_click(show_button)
show_button()