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)
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)
Hope that helps. Please comment below if this does not solve your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With