Dynamically changing dropdowns in IPython notebook

2019-02-04 14:35发布

问题:

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.

回答1:

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)


回答2:

import datetime
import ipywidgets as ipyw

from bokeh.models.widgets.inputs import AutocompleteInput
from IPython.display import display

dp1 = ipyw.Dropdown(options = ['Asia','Europe','Africa'])
dp2 = ipyw.Dropdown(options = ['India','China','Pakistan','Tibet'])
asia_list = ['India','China','Pakistan','Tibet']
europe_list = ['Germany','France','Italy']
africa_list = ['south africa','Nigeria','Kenya']
global_vbox = ipyw.VBox()
global_vbox.children = [dp1,dp2]
display(global_vbox)
def continent_change_event(x):
    global dp1
    global dp2
    list_name = dp1.value
    dp2.index = None #This line is very important for setting the values for widgets other than widget with observe method
    dp2.index = 0
    if(list_name == 'Asia'):
        dp2.options = asia_list
    elif(list_name == 'Europe'):
        dp2.options = europe_list
    else:
        dp2.options = africa_list

dp1.observe(continent_change_event)