投票最多的答案很有用,但对我来说似乎有点笨拙。搜索了一段时间后,我发现这里基于Jupyter docs的答案更适合我。我对它们进行了改编并提供了以下内容。
from ipywidgets import interact, Dropdown
geo = {'USA':['CHI','NYC'],'Russia':['MOW','LED']}
countryW = Dropdown(options = geo.keys())
cityW = Dropdown()
def update_cityW_options(*args): # *args represent zero (case here) or more arguments.
cityW.options = geo[countryW.value]
cityW.observe(update_cityW_options) # Here is the trick, i.e. update cityW.options based on countryW.value.
@interact(country = countryW, city = cityW)
def print_city(country, city):
print(country, city)
作为替代方案,我还发现我可以只更新cityW.options
insideprint_city
函数,更清晰的做法!
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] # Here is the trick, i.e. update cityW.options based on country, namely countryW.value.
print(country, city)