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

标签 python python-3.x drop-down-menu widget jupyter-notebook

我正在按照有关如何从此处处理 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)都有一些地区,我想要第三个下拉列表,每次更新城市时都会更改。

希望问题清楚,谢谢!

最佳答案

以防万一您从未找到解决方案:我这里有一个适用于 python 3 的解决方案。我已经注释了我从原始代码更改的所有内容。希望对您有所帮助!

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)

关于python - Jupyter notebook 上的多个依赖小部件(下拉菜单),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48407059/

相关文章:

python - 使用 heapq 降序

python - 只要在 python 中使用 selenium 页面上存在元素,如何使 while 循环运行?

Python 3.7.1 try except block 在命令行中以错误的顺序发生

python - 为什么 timeit.timeit 在使用变量时会出错?

wordpress - 试图使主题下拉菜单 OnClick 而不是悬停

python - 使用 imshow 将连续图像/数组显示为 python 中的重复动画

python - 使用 python 运行 cmd 命令(停止/启动服务)

python-3.x - 如何使用 Locust 提取性能测试的请求/秒(吞吐量)?

c# - 如何在下拉列表中添加表字段的2列值

ios - 为什么 YouTube 会干扰 iPad 悬停下拉菜单?