pythonbuttononclickgridipywidgets

adding on_click methods to buttons created with ipywidgets


I am using ipywidgets to create a dashboard.

I create a bunch of buttons using a loop:

from ipywidgets import GridspecLayout

grid = GridspecLayout(4, 3)
def create_expanded_button(description, button_style):
    return Button(description=description, button_style=button_style, layout=Layout(height='auto', width='auto'))


for i in range(4):
    for j in range(3):
        grid[i, j] = create_expanded_button('Button {} - {}'.format(i, j), 'warning')
grid

This is the code in the documentation. With such a code you create a dashboard with 16 buttons:

enter image description here

The question is what is the strategy as to how to handle every on_click methods of the buttons since all the buttons are called the same. Do the buttons have a kind of 'id'?

imagine that by clicking every button I want to fetch a particular data online. how to proceed?

thanks.


Solution

  • Try this:

    def on_btn_click(btn):
        if btn.description == 'Button 0 - 0':
            # do something on Button 0 - 0 click
        elif btn.description == 'Button 0 - 1':
            # do something on Button 0 - 1 click
        ...
    
    
    for i in range(4):
        for j in range(3):
            grid[i,j].on_click(on_btn_click)