How to change sliders programmatically

I’m starting out with Streamlit and I’m loving it. Such a refreshingly different paradigm! :slight_smile:

But here a question: I use multiple st.sliders for input values to my graphs. It would be nice to reset the sliders to some special predetermined positions when I press some button.

So how can I change sliders programmatically?

You can’t (as far as I can tell) change them programatically. You can set a default value, but since the widget key will change if you change this it causes some problems if you use buttons. Using a selectbox looks like it gets around this (as that’s then persistent):

import streamlit as st

defaults = st.selectbox("Choose defaults",
                        [
                            {"name": "Zeros",
                             "slider1": 0,
                             "slider2": 0
                            },
                            {"name": "Two and three",
                             "slider1": 2,
                             "slider2": 3
                            },
                        ],
                        format_func=lambda option:option["name"]
)

slider = st.slider("set value", min_value=0, value=defaults["slider1"], max_value=10)

st.write(f"Slider value: {slider}")

slider_2 = st.slider("set value 2", min_value=0, value=defaults["slider2"], max_value=10)

st.write(f"Slider value: {slider_2}")
2 Likes

Thanks @Ian_Calvert. Interesting approach. Doesn’t get 100% though where I want to get to: With a button I have the problem that I have to put something in the else branch (Button not pressed), and this then will sometimes reset the slider…

Also, another goal is to make two sliders depending on each other: A Start date slider and a End date slider. Both sliders can slide over the whole date range and then redraw each other so that the start date slider is always “left” of the end date slider. - I guess that’s not possible, right?

With a button I have the problem that I have to put something in the else branch (Button not pressed), and this then will sometimes reset the slider…

Yeah buttons are only true on the next run of the code, using them needs to be done quite carefully so I prefer stateful components. Particularly when they affect others.

If you’re explicitly after a slider, then you can just pass two values into the slider for the default value and it becomes a range slider. You might need to do some conversion to get dates though as I think it only supports numeric values.

Otherwise no, I don’t think you can make two sliders depend on each other