有没有办法在散景中的CheckboxButtonGroup
中循环按钮对象?
我想遍历组中的每个按钮,并根据其标签为它们分配不同的on_click
处理程序。我想象的是:
for button in checkbox_button_group:
button.on_click(someHandlerFunc)
但显然CheckboxButtonGroup对象不可迭代。查看文档我找不到找到返回组内实际按钮对象的属性。我看到active
属性和labels
,但这似乎不是我想要的。 (https://bokeh.pydata.org/en/latest/docs/reference/models/widgets.groups.html#bokeh.models.widgets.groups.AbstractGroup)
答案 0 :(得分:1)
在复选框组回调中,只需获取活动按钮的索引或标签即可。然后执行if / elif / else语句链,调用你想要与每个按钮关联的函数。
编辑:这里有一些简单的按钮组:
只需点击最后一个按钮
即可from bokeh.io import curdoc
from bokeh.models import CheckboxButtonGroup
a = CheckboxButtonGroup(labels=list('012'),active=[])
def stuff_0(in_active):
if in_active:
print 'do stuff'
else:
print 'undo stuff'
def stuff_1(in_active):
if in_active:
print 'yes'
else:
print 'no'
def stuff_2(in_active):
if in_active:
print 'banana'
else:
print 'apple'
stuff_list = [stuff_0,stuff_1,stuff_2]
def do_stuff(attr,old,new):
print attr,old,new
last_clicked_ID = list(set(old)^set(new))[0] # [0] since there will always be just one different element at a time
print 'last button clicked:', a.labels[last_clicked_ID]
last_clicked_button_stuff = stuff_list[last_clicked_ID]
in_active = last_clicked_ID in new
last_clicked_button_stuff(in_active)
a.on_change('active',do_stuff)
curdoc().add_root(a)
或者,您可以循环浏览按钮,并在每次单击按钮时使用所有按钮执行操作:
def do_stuff(attr,old,new):
print attr,old,new
for i in [0,1,2]:
stuff = stuff_list[i]
in_active = i in new
stuff(in_active)