基于Streamlit会话状态解决复选框切换时数据编辑器值重置问题
Solution using Streamlit Session State
Step 1: Initialize Session State with Default DataFrame
Store the initial DataFrame in st.session_state to preserve its values across app reruns, preventing the Value column from resetting when checkboxes are toggled.
import streamlit as st import pandas as pd # Initialize session state DataFrame if it doesn't exist if 'df' not in st.session_state: st.session_state.df = pd.DataFrame( data={'Value': [0, 0, 0, 0], 'Active': [False, False, False, False]}, index=['A', 'B', 'C', 'D'] )
Step 2: Create Checkboxes to Toggle Active Status
Generate checkboxes for each key (A-D) and sync their state with the Active column in the session state DataFrame.
# Create checkboxes for each index and update Active status for idx in st.session_state.df.index: current_active = st.session_state.df.loc[idx, 'Active'] new_active = st.checkbox(f"Activate {idx}", value=current_active) st.session_state.df.loc[idx, 'Active'] = new_active
Step 3: Filter and Edit Active Rows
Filter the DataFrame to show only rows where Active is True, then use st.data_editor to let users modify the Value column. Update the session state DataFrame with edited values to preserve changes.
# Filter to get active rows (only Value column) active_rows = st.session_state.df[st.session_state.df['Active']][['Value']] # Let user edit the active rows' values edited_values = st.data_editor(active_rows, num_rows="fixed") # Update the session state DataFrame with edited values st.session_state.df.update(edited_values)
Full Working Code
Combining all parts, here's the complete script:
import streamlit as st import pandas as pd # Initialize session state DataFrame if 'df' not in st.session_state: st.session_state.df = pd.DataFrame( data={'Value': [0, 0, 0, 0], 'Active': [False, False, False, False]}, index=['A', 'B', 'C', 'D'] ) # Checkboxes to toggle Active status for idx in st.session_state.df.index: current_active = st.session_state.df.loc[idx, 'Active'] new_active = st.checkbox(f"Activate {idx}", value=current_active) st.session_state.df.loc[idx, 'Active'] = new_active # Filter active rows and allow editing active_rows = st.session_state.df[st.session_state.df['Active']][['Value']] edited_values = st.data_editor(active_rows, num_rows="fixed") st.session_state.df.update(edited_values) # Optional: Display full DataFrame for verification st.subheader("Full DataFrame (for verification)") st.dataframe(st.session_state.df)
How It Works
- Session State Storage: The DataFrame is saved in
st.session_state, so its values are retained between reruns triggered by checkbox clicks. - Checkbox Sync: Each checkbox's state is linked directly to the
Activecolumn in the session state DataFrame, ensuring toggles update the DataFrame immediately. - Preserving Edits: When users modify values in
st.data_editor, the edited data is merged back into the session state DataFrame usingupdate(), so changes persist even when other checkboxes are toggled.
内容的提问来源于stack exchange,提问作者Davi Augusto Bandeira
相关产品推荐
相关产品推荐

