'ipywidgets jslink - non direct mappings

import ipywidgets as widgets
from IPython.display import display

slider = widgets.IntSlider(min=0, max=100, step=1, description='Age:', value = 0)
agelabel = widgets.Label(value = '0')

mylink = widgets.jslink((slider, 'value'), (agelabel, 'value'))
display(slider, agelabel)

In the first two lines after imports, we created a slider to choose age from and a label to display a message. This code works as expected and displays the slider's value in label as we move it.

Now, instead of displaying the direct value from slider, we want to show in label Your selected age : 12 or even apply some logic You may not order alcoholic drinks at 12.

Essentially getting the callback but not restriced to the mapped attributes value of these controls (((slider, 'value'), (agelabel, 'value'))).



Solution 1:[1]

I found a solution, though not through jslink. Many widgets, including IntSlider exposes observe which takes a callback function. Every time the slider is changed, the callback function gets called.

# mylink = widgets.jslink((slider, 'value'), (lblSlider, 'value'))

def showmsg(caller):
    lblSlider.value = f'Your age is {caller.new}'

slider.observe(showmsg, names='value')

We will not require to use jslink linking in this approach. Also note, names in observe which was used to specify when handler is called. Please see the docstring.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1