Gustavo
Gustavo

Reputation: 65

ipywidgets: Automatically update variable and run code after altering widget value

I have been trying to automatically update a variable and run a code snippet after altering a ipywidget.

So far the only partial solution I have found is to declare a global variable kind of following the example on the github (here):

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

Ideally what I am trying to achieve is to automatically change the x value after altering the widget without the use of global variables and also change some previously defined variables. It would be something like this:

x = 5
y = []
slider = widgets.IntSlider()
slider.value = x
def on_change(v):
   x = v['new']
   y.append(x)
slider.observe(on_change, names='value')
display(slider)

Upvotes: 3

Views: 5462

Answers (1)

ac24
ac24

Reputation: 5575

One way to achieve this would to be to make a class that accepts the new widget value, and does the derived calculation as well. I've done a simple addition but you could append to a list.

import ipywidgets as widgets

class Updated:

    def __init__(self):
        self.widget_value = None
        self.derived_value = None

    def update(self, val_dict) -> None:
        self.widget_value = val_dict['new']
        self.derived_value = self.widget_value + 10

update_class = Updated()

x = 5
y = []
slider = widgets.IntSlider()
slider.value = x

def on_change(v):
    update_class.update(v)
slider.observe(on_change, names='value')
display(slider)

You can then see how update_class.widget_value and update_class.derived_value change as you move the slider.

Upvotes: 6

Related Questions