Programatically setting widget values and bookmarking app state

Hi all,

I ran into some trouble with getting and setting query parameters yesterday, but found a solution which I would like to share. It relies on a few of the well-known hacks, and allows the definition of predefined states accessible by the push of a button. In addition, it showcases how the experimental get and set query parameters can be used, inspired by this comment. Hope the snippet is useful for some people :slight_smile:

import streamlit as st
import session_state
from streamlit.script_runner import RerunException
from streamlit.script_request_queue import RerunData

query_params = st.experimental_get_query_params()

state = session_state.get(
    session_id=0, first_query_params=st.experimental_get_query_params()
)
first_query_params = state.first_query_params

default_values = {
    "my_checkbox": int(state.first_query_params.get("my_checkbox", [0])[0]),
    "my_radio_button": int(state.first_query_params.get("my_radio_button", [2])[0]),
    "my_slider": int(state.first_query_params.get("my_slider", [1])[0]),
    "my_slider_with_two_values": (
        int(state.first_query_params.get("my_slider_with_two_values_min", [5])[0]),
        int(state.first_query_params.get("my_slider_with_two_values_max", [100])[0]),
    ),
    "my_multiselect": state.first_query_params.get("my_multiselect", ["Option 1"]),
}

my_checkbox = st.checkbox(
    "Tick me!", key=state.session_id, value=default_values["my_checkbox"]
)
query_params["my_checkbox"] = int(my_checkbox)

my_radio_options = ["Eat", "Sleep", "Both"]

my_radio_button = st.radio(
    "Options",
    my_radio_options,
    key=state.session_id,
    index=default_values["my_radio_button"],
)
query_params["my_radio_button"] = my_radio_options.index(my_radio_button)

my_slider = st.slider(
    "Slider",
    min_value=0,
    max_value=200,
    key=state.session_id,
    value=default_values["my_slider"],
)
query_params["my_slider"] = my_slider

my_slider_with_two_values = st.slider(
    "Slider with two values",
    min_value=0,
    max_value=100,
    key=state.session_id,
    value=default_values["my_slider_with_two_values"],
)
query_params["my_slider_with_two_values_min"] = my_slider_with_two_values[0]
query_params["my_slider_with_two_values_max"] = my_slider_with_two_values[1]

my_multiselect = st.multiselect(
    "Select options!",
    ["Option 1", "Option 2", "Option 3"],
    key=state.session_id,
    default=default_values["my_multiselect"],
)
query_params["my_multiselect"] = my_multiselect

if st.sidebar.button("Set predefined filtering"):
    state.first_query_params = dict(
        my_checkbox=[1],
        my_radio_button=[0],
        my_slider_with_two_values_min=[15],
        my_multiselect=["Option 2"],
    )
    state.session_id += 1
    raise RerunException(RerunData())

st.experimental_set_query_params(**query_params)
1 Like