hhprogram
hhprogram

Reputation: 3157

Bokeh: How to loop through CheckboxButtonGroup

Is there a way to loop through the button objects in a CheckboxButtonGroup in bokeh?

I want to loop through each button in the group and assign them different on_click handlers depending on their label. I was envisioning something like:

for button in checkbox_button_group:
    button.on_click(someHandlerFunc)

But obviously a CheckboxButtonGroup object is not iterable. Looking the documentation I cannot find to find an attribute that returns the actual button objects within the group. I see the active attribute and the labels but that doesn't seem like that is what I want.

https://docs.bokeh.org/en/latest/docs/reference/models/widgets.groups.html#bokeh.models.widgets.groups.AbstractGroup

Upvotes: 1

Views: 1347

Answers (1)

Seb
Seb

Reputation: 1775

In the checkboxgroup callback, just get the index or label of the active button. Then do a if/elif/else chain of statements calling whatever function you want associated with each button.

EDIT: here are some simple things with button groups:

To just do something with the last button clicked

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)

Or you can loop through the buttons and do stuff with all the buttons each time a button is clicked:

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)

Upvotes: 2

Related Questions