7

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)
Ashish
  • 729
  • 1
  • 9
  • 23
  • For someone struggling like me, declaring `global a` solves the problem. Not the most elegant solution. but that's how I got through it. – Ashish Jul 19 '17 at 12:29
  • while declaring a global may work for this type of problem I'd advise against doing that for a mutable variable checkout the answers to [this question](https://stackoverflow.com/questions/19158339/why-are-global-variables-evil) for more on why not to use globals. – James Draper Jul 19 '17 at 18:24
  • I know drawbacks of using global, agree with you completely. – Ashish Jul 20 '17 at 11:32

1 Answers1

12

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.

James Draper
  • 5,110
  • 5
  • 40
  • 59
  • 1
    Thanks! It did solve the problem. This is in fact only a sample problem, the real problem has a dictionary of widgets (checkboxes) which were loaded `on_click`. But, I could pass the complete dictionary through `values`, so it all worked perfectly. – Ashish Jul 20 '17 at 11:42
  • 6
    Seems complicated for just returning a value. Has this been improved since? – newbie Jun 09 '20 at 15:27