Have to press slider multiple times to set value

I have a multi page app with common sliders between the pages. So if foo has a default of 5, and on page one the user sets foo to 3, then when they select page two foo should have the value of 3.

Here is a MWE

import streamlit as st

if "foo" not in st.session_state:
    st.session_state.foo =5

st.session_state.foo = st.sidebar.slider("foo",min_value=0, max_value=10, step=1,value=st.session_state.foo)

double-clicking-slider

How can I ensure the user only has to press once?

There’s a trick to make this work for a multipage app, which is

  1. Use key to automatically sync the widget’s current value with session state.

  2. Put these lines at the top of your page, before you do any other streamlit calls:

for k, v in st.session_state.items():
    st.session_state[k] = v

These lines effectively tell streamlit that all of your session state values have been set manually, so they should be persisted even if the widget temporarily disappears off the page (e.g. when you switch pages).

e.g.

import streamlit as st

for k, v in st.session_state.items():
    st.session_state[k] = v

st.write("Page 1")

foo = st.slider("foo", min_value=0, max_value=10, step=1, key="slider")

st.write(foo)
import streamlit as st

for k, v in st.session_state.items():
    st.session_state[k] = v

st.write("Page 2")

foo = st.slider("foo", min_value=0, max_value=10, step=1, key="slider")

st.write(foo)
1 Like

Thanks @blackary, this works great.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.