Multiple interaction commands () duplicate widgets in IPython

I am using IPython Jupyter. In the following situation, I call a function with interact(), which alternately calls the second function with interact().

def fun1(dataset_id):
     dataset = read_dataset(dataset_id)
     interact(fun2, data=dataset, var=(0,dataset.property,0.1))

def fun2(data, var):
     # something

interact(fun1, dataset_id=(0,5,1))

At the first start, it displays two slider widgets: one for dataset_idand one for a variable var. But if I change the slider dataset_idonce, the second slider for is varadded below the first slider var, so now I have 3 sliders. How can i avoid this?

+4
source share
3 answers

, :

from ipywidgets import *
from IPython.display import display

datasets=[{"property":1},{"property":2},{"property":3},{"property":4},{"property":5}]

def read_dataset(dataset_id):
    return datasets[dataset_id]

def fun1(dataset_id):
    global sliders
    try:
        sliders.close()
    except NameError:
        pass
    dataset = read_dataset(dataset_id)
    sliders =  interactive(fun2, data=fixed(dataset), var=(0,dataset["property"],0.1)) # note I am now using interactive, instead of interact, because I need the close() function
    display(sliders)

def fun2(data, var):
    print var

interact(fun1, dataset_id=(0,5,1))
+1

(, , 100%, ). , .close() , . , , .

, , - .

from ipywidgets import *
from IPython.display import display

datasets=[{"property":1},{"property":2},{"property":3},{"property":4},{"property":5}]

def read_dataset(dataset_id):
    return datasets[dataset_id]

def fun1(dataset_id):
    dataset = read_dataset(dataset_id)
    sliders = interactive(fun2, data=fixed(dataset), var=(0,dataset["property"],0.1)) # note I am now using interactive, instead of interact, because I need the close() function
    close_button = widgets.Button(description="Remove sliders")
    def remove_sliders(b):
        sliders.close()
        b.close()
    close_button.on_click(remove_sliders)
    display(sliders)
    display(close_button)

def fun2(data, var):
    print
    # something

interact(fun1, dataset_id=(0,5,1))
0

: "" , :

import ipywidgets as widgets
from ipywidgets import *
from IPython.display import display

datasets=[{"property":1},{"property":2},{"property":3},{"property":4},{"property":5}]

def read_dataset(dataset_id):
    return datasets[dataset_id]

w_slider1 = IntSlider(min=0, max=len(datasets)-1, step=1)
w_slider2 = FloatSlider(min=0, step=0.1)

def fun1(dataset_id):
    dataset = read_dataset(dataset_id)
    #you could get rid of function "read_dataset"
    #dataset = datasets[dataset_id]
    w_slider2.max = dataset['property']

def fun2(data, var):
    #call fun1 to update the size of 2nd slider
    fun1(data)
    #do something
    print(data, var)

interact(fun2, data=w_slider1, var=w_slider2)
0

Source: https://habr.com/ru/post/1625519/


All Articles