Ond*_*rej 13 python ipython ipython-notebook
我在IPython笔记本(作为HTML小部件的一部分)和Spyre应用程序(作为dropdown元素)中有一个下拉列表,比如选择一个大陆,我想添加第二个下拉列表来选择该大陆的国家.现在很明显,第二个下拉列表中的选项取决于第一个下拉列表的值.我很难找到一种方便的方法来获得一个更新这个UI元素的回调函数.
我几乎在IPython笔记本中完成了这个,我有一个interact函数,在被调用的函数中,我interact用第二个下拉列表创建了第二个元素.但每当我更改第一个下拉列表时,都会创建一个新的下拉元素,因此每次更改时我都会得到一个额外的下拉列表.但我只希望更新一个下拉列表,就是这样.
希望问题很清楚.谢谢.
ILo*_*ing 20
使用interactive而不是interact更新您的小部件:
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.Select(options=geo.keys())
init = scW.value
cityW = widgets.Select(options=geo[init])
j = widgets.interactive(print_city, city=cityW)
i = widgets.interactive(select_city, country=scW)
display(i)
display(j)
Run Code Online (Sandbox Code Playgroud)
获得最多票数的答案很有用,但对我来说似乎有点笨拙。搜索了一段时间后,我发现这里基于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): # *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)
Run Code Online (Sandbox Code Playgroud)
作为替代,我还发现我可以只更新cityW.options内print_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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9069 次 |
| 最近记录: |