You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于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 Active column 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 using update(), so changes persist even when other checkboxes are toggled.

内容的提问来源于stack exchange,提问作者Davi Augusto Bandeira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 02:26:00