Dynamically changing dropdowns in IPython notebook widgets and Spyre

Ondrej picture Ondrej · Feb 15, 2015 · Viewed 14.7k times · Source

I have a dropdown in an IPython notebook (as part of the HTML widgets) and in a Spyre app (as a dropdown element), say to pick a continent and I'd like to add a second dropdown to select the country within the continent. Now obviously the options within the second dropdown are dependent on the value of the first one. I'm struggling to find a convenient way to have a callback function that would update this UI element.

I have almost done this in the IPython notebook where I had one interact function and within the called function, I'd create a second interact element with the second dropdown. But whenever I'd change the first dropdown a new dropdown element would be created, so I'd end up with one additional dropdown with each change. But I only want one dropdown to be updated, that's all.

Hope the issue is clear. Thank you.

Answer

ILoveCoding picture ILoveCoding · Mar 29, 2015

Use interactive instead of interact and update your widget:

from IPython.html import widgets
from IPython.display import display

geo={'USA':['CHI','NYC'],'Russia':['MOW','LED']}

def print_city(city):
    print city

def select_city(country):
    cityW.options = geo[country]


scW = widgets.Select(options=geo.keys())
init = scW.value
cityW = widgets.Select(options=geo[init])
j = widgets.interactive(print_city, city=cityW)
i = widgets.interactive(select_city, country=scW)
display(i)
display(j)