When an app displays several identical controls, Streamlit needs a way to tell them apart. A widget key is an identifier for a widget. Streamlit usually generates keys from widget characteristics, but identical widgets can receive the same key and cause an error. section 4.2.1 section 4.6
Give each Delete button a key
A task list with a Delete button beside each task creates multiple buttons with the same label. Use enumerate to get each task’s index, then include it in the button’s key: delete_0, delete_1, and so on. The keys distinguish the buttons even though their visible labels match. section 4.2.1
for idx, task in enumerate(task_list):
task_col, delete_col = st.columns([0.8, 0.2])
task_col.checkbox(task.name, task.is_done)
if delete_col.button("Delete", key=f"delete_{idx}"):
pass
See the task loop with a unique key assigned to each Delete button. section 4.2.1
An explicitly keyed widget also exposes its value through st.session_state. For example, a selectbox with key="select_dim" can be read using st.session_state["select_dim"]. To set its value programmatically, assign the session-state value before the widget code runs; setting it after the widget has rendered is not allowed. section 7.6.2
Use keys for dashboard links
For a shareable dashboard URL, prefix keys for selected widgets with w:. Copy matching query parameters into session state before rendering the widgets, and only when the key is not already present. This avoids resetting the user’s selections on every rerun. The prefix is an app convention, not a requirement for all widget keys. section 7.6.3
Listing 7.2 Getting and setting query params
import streamlit as st
def get_param(key):
return st.query_params.get(key, None)
def set_widget_defaults():
for key in st.query_params:
if key.startswith('w:') and key not in st.session_state:
st.session_state[key] = get_param(key)
def set_params():
query_params_dict = {}
for key in st.session_state:
if key.startswith('w:'):
value = st.session_state[key]
query_params_dict[key] = value
st.query_params.from_dict(query_params_dict)
See how prefixed widget keys connect session state to query parameters. section 7.6.3
