Jupyter noteb上的多个依赖小部件(下拉菜单)

2024-04-26 13:10:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我从这里学习了如何在jupyter笔记本上处理多个依赖小部件的示例:

Dynamically changing dropdowns in IPython notebook widgets and Spyre

在该示例中,代码解决方案如下:

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)都有一些地区,我想要第三个下拉列表,每次更新一个城市时都会改变。在

希望问题是清楚的,谢谢!在


Tags: fromimport示例city列表ipythondisplaywidgets
2条回答

使用interactive对我来说有点笨拙。我已经为原始页面here中的两个依赖小部件提供了一个更清晰简洁的答案。下面我为多个依赖小部件提供我的答案。在

from ipywidgets import interact, Dropdown

geo = {'USA':['CHI','NYC'],'Russia':['MOW','LED']}
geo2={'CHI':['1','2'],'NYC':['3','4'],'MOW':['5','6'],'LED':['7','8']}

countryW = Dropdown(options = geo.keys())
cityW = Dropdown(options = geo[countryW.value]) # options = geo[countryW.value] is to remove inital error but not that necessary.
districtW = Dropdown()

@interact(country = countryW, city = cityW, district = districtW)
def print_city(country, city, district):
    cityW.options = geo[country] # Here is the trick, i.e. update cityW.options based on country, namely countryW.value.
    districtW.options = geo2[city] # Dittoo
    print(country, city, district)

另一种方法是使用显式更新函数,如下所示。请记住,更新速度可能不是那么快。代码运行良好。在

^{pr2}$

以防万一你找不到解决方案:我这里有一个在Python3中工作的解决方案。我已经注释了我从原始代码中更改的所有内容。我希望这有帮助!在

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)

相关问题 更多 >