ipywidgets:根据另一个小部件的结果更新一个小部件

ipywidgets: Update one widget based on results from another

我在 IPython 中使用小部件,允许用户重复搜索短语并在另一个小部件(selection 小部件)中查看结果(不同的标题),然后 select其中一个结果。

简而言之:

search_text = widgets.Text(description = 'Search') 
search_result = widgets.Select(description = 'Select table')

def search_action(sender):
    phrase = search_text.value
    df = search(phrase) # A function that returns the results in a pandas df
    titles = df['title'].tolist()
    search_result.options = titles

search_text.on_submit(search_action)

这曾经工作得很好,但在更新到最新版本的 ipywidgets(从 4.0.1 到 5.1.3)之后,它看起来像

search_selection.options = titles

产生以下错误(一个或两个,因人而异):

TraitError: Invalid selection
TypeError: 'list' object is not callable

从小部件根据其他小部件的搜索结果更新结果的意义上来说,它仍然有效,但它给出了一个错误。

根据另一个小部件的结果在一个小部件中设置选项的正确方法是什么?

(编辑:添加了更详细的错误消息)

我一个小时前遇到了这个问题。我在这里使用最小示例拼凑了一个解决方案:Dynamically changing dropdowns in IPython notebook widgets and Spyre,因为我自己的要求是有动态链接列表。我相信您将能够使用此解决方案来调整您的要求。

关键是pre-generate全部Dropdowns/Select。由于某些原因,w.options = l 仅设置 w._options_labels 而不是 w.optionsw 的选定值的后续验证将非常失败。

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)

最后请注意,获取小部件的大多数 up-to-date 状态并非易事。这些是

  • 直接来自 children 的值,通过 get_current_state。这个可以信任。
  • 来自交互式实例,通过 i.kwargs
  • 从提供的参数到 print_city

后两者有时会过时,出于各种原因我不想进一步了解。

希望对您有所帮助。

您可以在分配给 options 期间保留通知:

with search_result.hold_trait_notifications():
    search_result.options = titles

因此:

search_text = widgets.Text(description = 'Search') 
search_result = widgets.Select(description = 'Select table')

def search_action(sender):
    phrase = search_text.value
    df = search(phrase) # A function that returns the results in a pandas df
    titles = df['title'].tolist()
    with search_result.hold_trait_notifications():
        search_result.options = titles

请参阅下面 hmelberg 的解释

"The root of the error is that the widget also has a value property and the value may not be in the new list of options. Because of this, widget value may be "orphaned" for a short time and an error is produced."

错误的根源是小部件也有一个值 属性,并且该值可能不在新的选项列表中。因此,widget value 可能会短时间 "orphaned" 并产生错误。

解决方案是在将小部件值分配给小部件之前将小部件值分配给选项列表(如果需要,然后删除 value/option),或者如 Dan 所写:使用创建一个 hold_trait-notifications()

丹的方法是最好的。以上只是说明了问题的原因。

我遇到了类似的问题并解决了Registering callbacks to trait changes in the kernel

caption = widgets.Label(value='The values of range1 and range2 are synchronized')
slider = widgets.IntSlider(min=-5, max=5, value=1, description='Slider')

def handle_slider_change(change):
    caption.value = 'The slider value is ' + (
        'negative' if change.new < 0 else 'nonnegative'
    )

slider.observe(handle_slider_change, names='value')

display(caption, slider)

我想这个解决方案在 2016 年还不可用,或者我的问题与想象的不一样。