散景中相互依赖的小部件

时间:2016-07-06 05:49:39

标签: python widget bokeh

bokeh中,我想调整一个Select窗口小部件中的可能选项,具体取决于另一个Select窗口小部件中的选定值。我最小的不工作的例子是这样的:

from bokeh.io import output_notebook, show
from bokeh.layouts import column
from bokeh.models import CustomJS, ColumnDataSource
from bokeh.models.widgets import Select

output_notebook()

# data source
foods = {'fruit': ['apple', 'orange', 'cherry'],
        'veg': ['carrot', 'celery']}

source = ColumnDataSource(data=foods)

def change_options_in_choice2(source=source):
    '''this is probably the place for magic'''
    f = cb_obj.get('value')
    print(f)

# first choice
choice1 = Select(title="food group:", value='fruit',
                 options=list(foods.keys()),
                 callback=CustomJS.from_py_func(change_options_in_choice2))

# options for second choice depend on choice in first choice
choice2 = Select(title='food items:', value='apple',
                options=foods['fruit'])


# merge them
show(column(choice1, choice2))

实际上,即使我将食物组切换为 veg,我也只能在苹果,橙子樱桃中选择我的食物项目。不知何故,我希望我可以使用choice2中的回调更新choice1中的可能选项。我该怎么做?

1 个答案:

答案 0 :(得分:1)

受布莱恩(bigreddot)评论的启发,我成功地尝试了这一点。它可以与bokeh serve main.py

一起提供
'''
with inspiration from 
https://github.com/bokeh/bokeh/blob/master/examples/app/stocks/main.py
'''
from bokeh.io import curdoc
from bokeh.layouts import column
from bokeh.models.widgets import Select
# data source
foods = {'fruit': ['apple', 'orange', 'cherry'],
        'veg': ['carrot', 'celery']}
def change_options_in_choice2(attrname, old, new):
    '''this is probably the place for magic'''
    choice2.options = foods[new]
# first choice
choice1 = Select(title="food group:", value='fruit',
                 options=list(foods.keys()))
choice1.on_change('value', change_options_in_choice2)
# options for second choice depend on choice in first choice
choice2 = Select(title='food items:', value='apple',
                options=foods['fruit'])
widgets = column(choice1, choice2)
# initialize
curdoc().add_root(widgets)
curdoc().title = "Eat healthy!"