almapineda
almapineda

Reputation: 25

How to have multiple widget buttons perform different actions in Jupyter Notebook?

I am trying to make a series of buttons that take samples from a data set based on some scenario. I have a 3x2 group of buttons, each describing a different scenario. I can't seem to get them to perform their separate actions.

I think I understand how to connect the action of clicking a button to its response. However, I don't understand how to do the same for multiple buttons.

Here's my code that worked to get a single, standalone button to work:

button = widgets.Button(description='Generate message!')
out = widgets.Output()
def on_button_clicked(_):
    samp_text = raw_data.sample(1).column(1)
    # "linking function with output"
    with out:
      # what happens when we press the button
      print(samp_text)
# linking button and function together using a button's method
button.on_click(on_button_clicked)
# displaying button and its output together
widgets.VBox([button,out])

Now what I'm trying to do is take different kinds of samples given various situations. So I have functions written for each type of sampling method that returns a table of proportions:

1    47.739362
2    44.680851
3     4.920213
9     2.659574
Name: vote, dtype: float64

However the same method in the first example with just one button doesn't work the same with multiple. How do I use widgets.Output() and how do I connect it so that clicking the button outputs the corresponding sample summary?

I expect for a clicked button to output its sample summary as shown above.

Upvotes: 2

Views: 5590

Answers (2)

thesauravs
thesauravs

Reputation: 11

Created two buttons using the list. Guess code itself explains better.

from ipywidgets import Button, HBox

thisandthat = ['ON', 'OFF']

switch = [Button(description=name) for name in thisandthat]

combined = HBox([items for items in switch])

def upon_clicked(btn):
    print(f'The circuit is {btn.description}.', end='\x1b\r')
    for n in range(len(thisandthat)):
        switch[n].style.button_color = 'gray'
    btn.style.button_color = 'pink'

for n in range(len(thisandthat)):
    switch[n].on_click(upon_clicked)

display(combined)

Upvotes: 1

Aaron Watters
Aaron Watters

Reputation: 2846

I didn't have any problem extending your example to use multiple buttons. I don't know where you were confused.

multiple button example

Sometimes exceptions that occur in widget callbacks do not get printed -- maybe you had a bug in your code that you couldn't see for that reason. It's best to have everything wrapped in a "with out:"

Upvotes: 4

Related Questions