票数最高的答案虽然有用,但对我来说有些笨拙。经过一番搜索,我发现基于Jupyter文档的这里的答案更适合我。我进行了改编并提供以下内容。
from ipywidgets import interact, Dropdown
geo = {'USA':['CHI','NYC'],'Russia':['MOW','LED']}
countryW = Dropdown(options = geo.keys())
cityW = Dropdown()
def update_cityW_options(*args):
cityW.options = geo[countryW.value]
cityW.observe(update_cityW_options)
@interact(country = countryW, city = cityW)
def print_city(country, city):
print(country, city)
作为另一种选择,我还发现我可以在“print_city”函数内直接更新“cityW.options”,这是更加清晰的做法!
from ipywidgets import interact, Dropdown
geo = {'USA':['CHI','NYC'],'Russia':['MOW','LED']}
countryW = Dropdown(options = geo.keys())
cityW = Dropdown()
@interact(country = countryW, city = cityW)
def print_city(country, city):
cityW.options = geo[country]
print(country, city)
IPython.html.widgets
已经迁移到ipywidgets
。请使用import ipywidgets as widgets
。 - Kamil Sindi