Python:如何在bokeh中进行多项选择?

时间:2019-05-21 18:32:17

标签: python bokeh

我想从选择中选择一个子节。

我有一个如下数据框。

df = pd.DataFrame()
df['People'] = ['Eva', 'John', 'Paul','Mr a', 'Miss b', 'Mrs c' ]
df['Type']   = ['Students', 'Students', 'Students', 'Teachers', 'Teachers', 'Teachers']

假设我们有StudentTeachers

select  =  Select(title="People",  options=['Student', 'Teachers' ])

然后我们有三个学生:EvaJohnPaul和三个老师Mr aMiss bMrs c

我们如何创建第二个选择select2,如果我们选择教师并选择EvaJohn,那么他们会选择PaulMr aMiss bMrs c(如果我们选择Teachers)。

select2  =  Select(title="Selected",  options=[ (`Eva`, `John`, `Paul`), (Mr a`, `Miss b`, `Mrs c`)] ])

这就是我的想法

select_data = Select(title="Type",  options=['None', 'Students', 'Teachers' ], value = '')
dynamic_select = Select(title = 'People', value = ''  , 
                        options = ['None','Eva', 'John', 'Paul','Mr a', 'Miss b', 'Mrs c' ] )
controls = widgetbox(select_data, dynamic_select)
layout = column(row(controls))

def update_layout(attr, old, new):
        if select_data.value == 'Students':
            dynamic_select = Select(title = 'People', value = '', options = ['Eva', 'John', 'Paul'])
        if select_data.value == 'Teachers':
            dynamic_select = Select(title = 'People', value = '', options = ['Mr a', 'Miss b', 'Mrs c'])
        if select_data.value == 'None':
            dynamic_select = Select(title = 'People', value = '', options = ['None'])     


select_data.on_change('value', update_layout)
dynamic_select.on_change('value', update_layout)
curdoc().add_root(layout)

1 个答案:

答案 0 :(得分:1)

使用此代码,您可以动态添加/删除第二个Select小部件。这就是你想要的吗?

from bokeh.plotting import curdoc, show
from bokeh.models import Select, Column, Div
from datetime import datetime, timedelta
import numpy as np

students = ['Eva', 'John', 'Paul']
teachers = ['Mr a', 'Miss b', 'Mrs c']
select_data = Select(title="People",  options=['', 'Students', 'Teachers' ], value = '')
layout = Column(select_data)

def update_layout(attr, old, new):
    if new:
        if len(layout.children) > 1 and layout.children[len(layout.children) - 1].title != new:
            layout.children.remove(layout.children[len(layout.children) - 1])

        options = students if new == 'Students' else teachers
        dynamic_select = Select(title = '{}'.format(new), value = '', options = options)
        layout.children.append(dynamic_select)

select_data.on_change('value', update_layout)
curdoc().add_root(layout)

enter image description here