Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ipywidgets dropdown widgets: what is the onchange event?

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.?

like image 647
Tim Richardson Avatar asked Dec 01 '15 12:12

Tim Richardson


1 Answers

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.

like image 166
sfjac Avatar answered Sep 22 '22 15:09

sfjac