##// END OF EJS Templates
Address problems found in in-person review
Address problems found in in-person review

File last commit:

r17946:fd20d2a3
r17947:50b5a703
Show More
Widget Events.ipynb
233 lines | 5.3 KiB | text/plain | TextLexer

Index - [Back](Widget List.ipynb) - [Next](Widget Styling.ipynb)

Widget Events

Special events

In [ ]:
from __future__ import print_function

The Button is not used to represent a data type. Instead the button widget is used to handle mouse clicks. The on_click method of the Button can be used to register function to be called when the button is clicked. The doc string of the on_click can be seen below.

In [ ]:
from IPython.html import widgets
print(widgets.Button.on_click.__doc__)

Example

Since button clicks are stateless, they are transmitted from the front-end to the back-end using custom messages. By using the on_click method, a button that prints a message when it has been clicked is shown below.

In [ ]:
from IPython.display import display
button = widgets.Button(description="Click Me!")
display(button)

def on_button_clicked(b):
    print("Button clicked.")

button.on_click(on_button_clicked)

on_sumbit

The Text also has a special on_submit event. The on_submit event fires when the user hits return.

In [ ]:
text = widgets.Text()
display(text)

def handle_submit(sender):
    print(text.value)

text.on_submit(handle_submit)

Traitlet events

Widget properties are IPython traitlets and traitlets are eventful. To handle changes, the on_trait_change method of the widget can be used to register a callback. The doc string for on_trait_change can be seen below.

In [ ]:
print(widgets.Widget.on_trait_change.__doc__)

Signatures

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)

Using this method, an example of how to output an IntSlider's value as it is changed can be seen below.

In [ ]:
int_range = widgets.IntSlider()
display(int_range)

def on_value_change(name, value):
    print(value)

int_range.on_trait_change(on_value_change, 'value')

Index - [Back](Widget List.ipynb) - [Next](Widget Styling.ipynb)