问题描述
我正在关注如何从这里处理 jupyter 笔记本上的多个依赖小部件的示例:
I was following the example on how to handle multiple dependent widgets on jupyter notebooks from here:
在 IPython 笔记本小部件和 Spyre 中动态更改下拉列表
在该示例中,代码解决方案如下:
In that example the code solution was the following:
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.Dropdown(options=geo.keys())
init = scW.value
cityW = widgets.Dropdown(options=geo[init])
j = widgets.interactive(print_city, city=cityW)
i = widgets.interactive(select_city, country=scW)
display(i)
display(j)
所以,第二个下拉菜单取决于第一个下拉菜单的值.这里的问题是:如果我想创建依赖于第二个下拉列表的第三个下拉列表怎么办?假设上面的每个城市(CHI、NYC、MOW、LED)都有一些区,我想要第三个下拉菜单,每次更新城市时都会改变.
so, the second dropdown is dependent on the value of the first one.Here the question: What if i want to create a third dropdown that is dependent on the value of the second one? Let's say that each of the cities above (C NYC, MOW, LED) have some districts, and I'd like a third dropdown that change every time that a city is updated.
希望问题清楚,谢谢!
推荐答案
以防万一您从未找到解决方案:我这里有一个适用于 python 3 的解决方案.我已经评论了我对原始代码所做的所有更改.希望对你有帮助!
Just in case you never found a solution: I have one here that works in python 3. I've commented everything that I changed from the original code. I hope it helps!
from IPython.html import widgets
from IPython.display import display
geo={'USA':['CHI','NYC'],'Russia':['MOW','LED']}
geo2={'CHI':['1','2'],'NYC':['3','4'],'MOW':['5','6'],'LED':['7','8']} #create dictionary with city districts
def print_city(city,district):
print(city)
print(district) #add in command to print district
def select_city(country):
cityW.options = geo[country]
#add in 'select district' function that looks in the new dictionary
def select_district(city):
districtW.options = geo2[city]
scW = widgets.Dropdown(options=geo.keys())
init = scW.value
cityW = widgets.Dropdown(options=geo[init])
init2= cityW.value #new start value for district dropdown
districtW = widgets.Dropdown(options=geo2[init2]) #define district dropdown widget
j = widgets.interactive(print_city, city=cityW, district=districtW) #define district value
i = widgets.interactive(select_city, country=scW)
k = widgets.interactive(select_district, city=cityW) #call everything together with new interactive
display(i)
display(j)
这篇关于Jupyter notebook 上的多个依赖小部件(下拉菜单)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!