Search code examples
pythonmatplotlibslideripywidgets

Python - design a slider to control the input of a function


I have the following codes

def update(val):
    if val == 0:
        value = s.val
        ax1.cla()
        ax1.plot_surface(x, y, rm, cmap = cm.coolwarm, linewidth = 0, antialiased = False)        
    elif val == 1:
        value = s.val
        ax1.cla()
        ax1.plot_surface(x, y, rm1, cmap = cm.coolwarm, linewidth = 0, antialiased = False)
    elif val == 2:
        value = s.val
        ax1.cla()
        ax1.plot_surface(x, y, rm2, cmap = cm.coolwarm, linewidth = 0, antialiased = False)      
    
ax1.set_zlim(-110, -80)



slider = wg.IntSlider(value=1, min=1, max=3, description='this is     slider')
slideroutput = wg.Output()
display(slider, slideroutput)

def on_value_change(change):
    with slideroutput:
        print(change['new'])

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


update(slideroutput)
plt.show()

If the input of update is "i", it shows the i-th 3D graph in the definition of update function, where i = 1, 2, 3.

How to design a slider such that when I move the control button of the slider, the output of the slider is 1, 2 or 3, which will become the input of "update"?

For example

update(slider_button)

Thanks!


Solution

  • This is the function that you are looking for:

    import ipywidgets as wg
    
    slider = wg.IntSlider(value=1, min=1, max=3, description='this is slider')
    slideroutput = wg.Output()
    display(slider, slideroutput)
    
    def on_value_change(change):
        with slideroutput:
            print(change['new'])
    
    slider.observe(on_value_change, names='value')
    

    However, I strongly advice you to find another alternative (for example: dropdown list or button instead of slider). Slider use .observe. This causes the program to be very heavy, especially when used in correlation with 3D plot. The above code has simply print command, however, you can see that it doesn't run that smooth. You can imagine how much worse it is if linked with 3D plot.

    ---edit---

    numberonslider = []
    def on_value_change(change):
        
        with slideroutput:
            numberonslider.append(change['new'])
            print(numberonslider[-1])
    slider.observe(on_value_change, names='value')