如何使用 IPython Widgets 使参数可能值依赖于另一个参数?

got*_*ota 5 widget ipython jupyter jupyter-notebook ipywidgets

假设我在 Python 中有这个简单的函数:

def f(gender, name):
    if gender == 'male':
        return ranking_male(name)
    else:
        return ranking_female(name)
Run Code Online (Sandbox Code Playgroud)

其中gender属于['male', 'female']name属于['Adam', 'John', 'Max', 'Frodo'](如果gendermale)或['Mary', 'Sarah', 'Arwen'](否则)。

我想interactipywidgets这个功能申请f。通常一个会做

from ipywidgets import interact
interact(f, gender = ('male', 'female'), name = ('Adam', 'John', 'Max', 'Frodo'))
Run Code Online (Sandbox Code Playgroud)

问题是现在的可接受值name取决于为 选择的值gender

我试图在文档中找到它,但找不到。我认为唯一可能重要的是这是用于设置特征更改的动态通知。

    Parameters
    ----------
    handler : callable
        A callable that is called when a trait changes. Its
        signature should be ``handler(change)``, where ``change```is a
        dictionary. The change dictionary at least holds a 'type' key.
        * ``type``: the type of notification.
        Other keys may be passed depending on the value of 'type'. In the
        case where type is 'change', we also have the following keys:
        * ``owner`` : the HasTraits instance
        * ``old`` : the old value of the modified trait attribute
        * ``new`` : the new value of the modified trait attribute
        * ``name`` : the name of the modified trait attribute.
    names : list, str, All
        If names is All, the handler will apply to all traits.  If a list
        of str, handler will apply to all names in the list.  If a
        str, the handler will apply just to that name.
    type : str, All (default: 'change')
        The type of notification to filter by. If equal to All, then all
        notifications are passed to the observe handler.
Run Code Online (Sandbox Code Playgroud)

但我不知道该怎么做,也不知道如何解释文档字符串在说什么。任何帮助深表感谢!

mrg*_*oom 2

例如,您有brandmodel的汽车,并且model取决于brand

d = {'Volkswagen' : ['Tiguan', 'Passat', 'Polo', 'Touareg', 'Jetta'], 'Chevrolet' : ['TAHOE', 'CAMARO'] }

brand_widget = Dropdown( options=list(d.keys()),
                         value='Volkswagen',
                         description='Brand:',
                         style=style
                       )
model_widget = Dropdown( options=d['Volkswagen'],
                         value=None,
                         description='Model:',
                         style=style
                       )

def on_update_brand_widget(*args):
    model_widget.options = d[brand_widget.value]

brand_widget.observe(on_update_brand_widget, 'value')
Run Code Online (Sandbox Code Playgroud)