0

When I update the second slider whenever the first slider changes, then the function f is called twice

I understand why this is happening, but it causes some unwanted flicker in the output since it takes a bit to calculate what I actually want to show.

Minimal Working Example

import ipywidgets as widgets
ncalls =0
caption = widgets.Label(value='N Calls: ' + str(ncalls))
a = widgets.IntSlider(min=-5, max=5, value=1, description='a')
b = widgets.IntSlider(min=-5, max=5, value=1, description='b')

def handle_slider_change(change):
    b.value = change["new"] - change["old"] + b.value 

def f(a, b):
    global ncalls
    ncalls +=1
    caption.value = 'N Calls: ' + str(ncalls)
    print(a,b)

a.observe(handle_slider_change, names='value')
out = widgets.interactive_output(f, {"a":a, "b":b})
widgets.VBox([caption,a,b,out])
Peter Hansen
  • 464
  • 3
  • 9

1 Answers1

0

I don't see much flickering, although it looks like you have a more expensive function in the interactive. Could you describe what you want to happen a little more?

Maybe widgets.link will help compared to a.observe?

import ipywidgets as widgets
ncalls =0
caption = widgets.Label(value='N Calls: ' + str(ncalls))
a = widgets.IntSlider(min=-5, max=5, value=1, description='a')
b = widgets.IntSlider(min=-5, max=5, value=1, description='b')

def handle_slider_change(change):
    b.value = change["new"] - change["old"] + b.value 

def f(a, b):
    global ncalls
    ncalls +=1
    caption.value = 'N Calls: ' + str(ncalls)
    print(a,b)

widgets.link((a, 'value'), (b, 'value'))
out = widgets.interactive_output(f, {"a":a, "b":b})
widgets.VBox([caption,a,b,out])
ac24
  • 5,325
  • 1
  • 16
  • 31