wenhoo
wenhoo

Reputation: 362

Using on_trait_change in ipython notebook widgets

I'm trying to use the IntSlider widget in IPython.html.widgets, and I want to call a function whenever the slider value changes. Additionally, I want to pass multiple arguments into the function. I was able to use on_trait_change() to call a function but have no idea how to pass arguments:

def somefn(parameter1, parameter2):
   print (parameter1, parameter2)

slider = widgets.IntSlider(min=0,max=3,step=1)
slider.on_trait_change(somefn)

Upvotes: 2

Views: 1459

Answers (1)

Dan Schien
Dan Schien

Reputation: 1412

I would suggest using a partial.

from IPython.display import display
import ipywidgets as widgets

def somefn(parameter1,my_arg):
    print ("parameter1: {}".format(parameter1))
    print ("my_arg: {}".format(my_arg))

from functools import partial
somefn_arg_0 = partial(somefn, my_arg=0)

slider = widgets.IntSlider(min=0,max=3,step=1)
slider.observe(somefn_arg_0)
display(slider)

Note I have replaced the deprecated on_trait_change with observe.

Upvotes: 2

Related Questions