Ipywidgets: how to bind widget to variable

Created on 1 Feb 2018  路  7Comments  路  Source: jupyter-widgets/ipywidgets

Hello!

What is the simpliest way to bind value of some widget to some variable without displaying widget like in interact?

resolved-locked

Most helpful comment

Do you mean -- I have a slider (or some other widget), and I want to retrieve the value?

import ipywidgets as widgets
from IPython.display import display

slider = widgets.IntSlider()
display(slider)
# change the slider value
print(slider.value)

Most of the core widgets have a .value when they clearly reference a single value (e.g. sliders, text entries etc.).

screen shot 2018-02-01 at 19 46 05

All 7 comments

Do you mean -- I have a slider (or some other widget), and I want to retrieve the value?

import ipywidgets as widgets
from IPython.display import display

slider = widgets.IntSlider()
display(slider)
# change the slider value
print(slider.value)

Most of the core widgets have a .value when they clearly reference a single value (e.g. sliders, text entries etc.).

screen shot 2018-02-01 at 19 46 05

@pbugnion I mean I want to connect slider.value with some other variable x from my business object.
And when slider moves x should automatically change it's value.

Should I use observe method for this?

import ipywidgets as widgets
from IPython.display import display
x = 5
slider = widgets.IntSlider()
slider.value = x
def on_change(v):
    x = v['new'] 
slider.observe(on_change, names='value')
display(slider)

Yes, that's how to make x automatically update to the slider value.

Closing as answered. Please comment here again if you'd like to continue the discussion.

Im unable to update the variable this way unless I declare x as a global variable.

Im unable to update the variable this way unless I declare x as a global variable.

You have to, because you have modified x in the on_change function. The temporary x only exists in the function scope.

If the value, the widget, and the on_change() function are inside a class instance, then that also works.

Was this page helpful?
0 / 5 - 0 ratings