Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return output of the function executed 'on_click'

How to get the output of the function executed on_click by ipywidgets.Button outside the function to use in next steps? For example, I want to get back the value of a after every click to use in the next cell of the jupyter-notebook. So far I only get None.

from ipywidgets import Button
def add_num(ex):
    a = b+1
    print('a = ', a)
    return a

b = 1
buttons = Button(description="Load/reload file list")
a = buttons.on_click(add_num)
display(buttons)
print(a)
like image 312
Ashish Avatar asked Jul 19 '17 10:07

Ashish


1 Answers

The best way that I have found to do this type of thing is by creating a subclass of widgets.Button and then add a new traitlet attribute . That way you can load the value(s) that you want to perform operations on when you create a new button object. You can access this new traitlet attribute whenever you want inside or outside of the function. Here is an example;

from ipywidgets import widgets
from IPython.display import display
from traitlets import traitlets

class LoadedButton(widgets.Button):
    """A button that can holds a value as a attribute."""

    def __init__(self, value=None, *args, **kwargs):
        super(LoadedButton, self).__init__(*args, **kwargs)
        # Create the value attribute.
        self.add_traits(value=traitlets.Any(value))

def add_num(ex):
    ex.value = ex.value+1
    print(ex.value)

lb = LoadedButton(description="Loaded", value=1)
lb.on_click(add_num)
display(lb)

loaded button example screenshot Hope that helps. Please comment below if this does not solve your problem.

like image 149
James Draper Avatar answered Nov 11 '22 19:11

James Draper