ipywidgets dropdown widgets: what is the onchange event?

Between this link and the traitlet docs on github and just playing around, I finally figured this out:

w = widgets.Dropdown(
    options=['Addition', 'Multiplication', 'Subtraction', 'Division'],
    value='Addition',
    description='Task:',
)

def on_change(change):
    if change['type'] == 'change' and change['name'] == 'value':
        print("changed to %s" % change['new'])

w.observe(on_change)

display(w)

Overall this looks a lot richer than the deprecated interface, but it could definitely use more examples.


Put it all together

Inspired on previous answers and lambda expressions I use this:

def function(option):
    print(option)


w = widgets.Dropdown(
    options=['None', 'Option 1', 'Option 2', 'Option 3'],
    description='Option:',
    disabled=False
)

w.observe(
    lambda c: plot_content(c['new']) if (c['type'] == 'change' and c['name'] == 'value') else None
)

display(w)

You can specify the change name in observe. This makes for cleaner code, and the handler is not called for changes you don't need:

from IPython.display import display
from ipywidgets import Dropdown

def dropdown_eventhandler(change):
    print(change.new)

option_list = (1, 2, 3)
dropdown = Dropdown(description="Choose one:", options=option_list)
dropdown.observe(dropdown_eventhandler, names='value')
display(dropdown)