I can register a handler to button.on_click in ipython notebook widgets, but I don't know how to do the same for a dropdown widget
import ipywidgets as widgets from IPython.display import display def on_button_clicked(b): print("Button clicked.") button = widgets.Button(description="Click Me!") display(button) button.on_click(on_button_clicked)
But for
choose_task = widgets.Dropdown( options=['Addition', 'Multiplication', 'Subtraction'], value='Addition', description='Task:', )
there seems to be only
on_trait_change(...)
if I register a handler with this, can I use it to access the value of the widget? I have seen examples with the handler and the widget belong to a subclass, and the handler can use self to introspect. But if I don't want to use a subclass, how does the handler know what widget was the target of the 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With