James Owers
James Owers

Reputation: 8345

Getting the current value of an IPython widget from within a loop

I'd like to get the values of the slider widgets within some loop. However, I would like these to update in real time.

For example see below. In the code pictured, I initialise some sliders, then run the loop below. Whilst the loop is running I move the sliders around. The printed values from the loop do not change from the initial value. When I execute the last cell, the updated slider values are shown.

enter image description here

Upvotes: 1

Views: 2815

Answers (1)

James Owers
James Owers

Reputation: 8345

Here's a solution inspired by the last example in asyncronous widgets (as suggested by @Fabio Perez):

import threading
from IPython.display import display
import ipywidgets as widgets
def f(a, b):
    return

w = interactive(f, a=10, b=20)

def work(w):
    for ii in range(10):
        time.sleep(1)
        print(w.kwargs, w.result)

thread = threading.Thread(target=work, args=(w,))
display(w)
thread.start()

This starts a separate thread which checks the values of the widgets.

Upvotes: 1

Related Questions