我一小时前就遇到了这个问题。我使用这里的最小示例编写了一个解决方案:动态更改 IPython 笔记本小部件和 Spyre 中的下拉菜单,因为我自己的要求是拥有动态链接列表。我相信您将能够使用此解决方案来适应您的要求。
关键是预先生成所有下拉菜单/选择。因为某些原因,w.options = l
仅套w._options_labels
但不是w.options
。随后验证所选值w
然后就会惨败。
import ipywidgets as widgets
from IPython.display import display
geo={'USA':['CHI','NYC'],'Russia':['MOW','LED']}
geoWs = {key: widgets.Select(options=geo[key]) for key in geo}
def get_current_state():
return {'country': i.children[0].value,
'city': i.children[1].value}
def print_city(**func_kwargs):
print('func_kwargs', func_kwargs)
print('i.kwargs', i.kwargs)
print('get_current_state', get_current_state())
def select_country(country):
new_i = widgets.interactive(print_city, country=countryW, city=geoWs[country['new']])
i.children = new_i.children
countryW = widgets.Select(options=list(geo.keys()))
init = countryW.value
cityW = geoWs[init]
countryW.observe(select_country, 'value')
i = widgets.interactive(print_city, country=countryW, city=cityW)
display(i)
最后请注意,获取小部件的最新状态并非易事。这些都是
- 直接来自孩子们的价值观,通过
get_current_state
。这是可以信赖的。
- 从交互式实例中,通过
i.kwargs
- 从提供的参数到
print_city
后两者有时可能会过时,由于各种原因我不想进一步了解。
希望这可以帮助。