In the example of "Widgets Events" of the ipywidgets doc, I knew that button.on_click can call a function without parameters. But suppose that I define a str variable a, and a function
def fun(a):
print(a)
I would like to call this 'fun' function when I click the button, but I don't know how to give the parameter a to the function fun. Thank you for your kind help!
How about calling the fun function in the on_button_clicked function?
import ipywidgets as widgets
from IPython.display import display
button = widgets.Button(description="Click Me!")
display(button)
def fun(a):
print(a)
def on_button_clicked(b):
fun('a')
button.on_click(on_button_clicked)
Thanks for commenting with a solution, @jtpio. @monchin, I agree completely with @jtpio.
@jtpio Thank you very much! It worked for me!
Glad it worked!
Hi,
I have a follow up question! What if I need 'a' to be passed as an argument to the function and not just a hardcoded string? For e.g. I want to do something like:
def on_button_clicked(b, random_string):
fun(random_string)
button.on_click(on_button_clicked, 'abcdefg')
Is there a way to achieve this? Basically, pass an argument to an ipywidget event handler function?
Thanks!
-Rishabh
I would use functools.partial for something like that
I'm not sure how to use that, but I built another function that would initialize the "random_string" variable in my ".py" package, and then used this already initialized "random_string" in the callback function (event handler function)
@rishabhmulani It would be something like this:
import functools
def on_button_clicked(b, rs_="some_default_string"):
fun(rs_)
button.on_clicked(functools.partial(on_button_clicked, rs_="abcdefg"))
Most helpful comment
How about calling the
funfunction in theon_button_clickedfunction?