Streamlit slider resetting when changing max_value


I have 2 sliders. The first slider (μ) determines the max_value for the second slider (σ²). Works great with the following code except for a major issue:

mu = st.slider('$mu$', 0.0, 5.0, 1.0, step=0.1)
var = st.slider('$sigma^2$', 0.0, mu, 1.0, step=0.1)

The issue is that change mu, resets the value of the var slider back to 1.0. How do I have the var slider change its max_value from mu without affecting its currently set value? Is Streamlit’s session_state mechanism appropriate here? It’s very important for this app to allow users the ability to have multiple tabs open with different values for mu and var in each tab. Is each tab a separate session?

Here’s the MRE with code:

I was able to accomplish what I wanted with session_state. Is this the right use of session_state?

mu = st.slider('$mu$', 0.0, 5.0, 2.5, step=0.1)
var = st.slider('$sigma^2$', 0.0, mu, min(mu, st.session_state.var) if 'var' in st.session_state else 1.0, step=0.1, key='var')

Seems to work, even across tabs (no sharing of state, which is what I needed), but the σ² slider no longer slides! The μ slider does slide and update values as you slide. But if you try and slide the σ² slider, it stops the moment values are updated and you have to click and drag it again. Any idea what’s happening?

Asked By: at.



The issue is that when you interact with a widget, Streamlit reruns your code – so when you interact with mu, the value of var gets set back to whatever it would be when the slider first loads.

One way to get around this is to make both sliders part of the same form, which would prevent your app from rerunning until you hit the submit button.

import streamlit as st

with st.form("slider_form"):
    mu = st.slider('$mu$', 0.0, 5.0, 1.0, step=0.1)
    var = st.slider('$sigma^2$', 0.0, mu, 1.0, step=0.1)
    submit = st.form_submit_button("Submit Slider Values")

Update: looks like you got an answer to this question here as well. I’ll paste Debbie’s response below.

you can get around this by not using the default value to change its
value and instead using session_state to assign it.

Here is a more robust solution that avoids the error. I didn’t know
how you wanted to handle mu == 0.0 so I just hid the second slider.
You can avoid a few of these lines if you don’t allow mu to go to zero
and break the second slider.

import streamlit as st

if 'default' not in st.session_state:
    st.session_state.default = 1.0

def set_default():
    if 'var' in st.session_state:
        st.session_state.default = min(st.session_state.var,

mu = st.slider('$mu$', 0.0, 5.0, 2.5, step=0.1, key='mu', on_change=set_default)

if mu > 0.0:
    var = st.slider('$sigma^2$', 0.0, mu, st.session_state.default, step=0.1, key='var')
Answered By: Caroline Frasca
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.