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

Streamlit多提交状态保持问题:双独立图表对比功能异常

解决方案:Streamlit双列独立操作+状态留存实现

核心思路

给左右两列分配独立的Session State键,分别存储各自的参数配置和生成的图表对象,确保操作一侧时不会影响另一侧的已保存状态;同时通过条件渲染避免未配置参数时的报错。

完整代码示例

import streamlit as st
import pandas as pd
import plotly.express as px

# 初始化Session State,为左右列分别创建独立状态容器
if "left_config" not in st.session_state:
    st.session_state.left_config = {"data_path": "", "x_col": "", "y_col": "", "fig": None}
if "right_config" not in st.session_state:
    st.session_state.right_config = {"data_path": "", "x_col": "", "y_col": "", "fig": None}

# 布局:拆分左右两列
col1, col2 = st.columns(2)

# 左列操作区
with col1:
    st.subheader("左侧数据集")
    with st.form(key="left_form"):
        # 输入框绑定对应列的Session State值,实现状态回显
        data_path = st.text_input("输入数据集路径", value=st.session_state.left_config["data_path"])
        x_col = st.text_input("X轴列名", value=st.session_state.left_config["x_col"])
        y_col = st.text_input("Y轴列名", value=st.session_state.left_config["y_col"])
        submit_left = st.form_submit_button("生成折线图")
    
    # 提交后更新左列状态并生成图表
    if submit_left:
        try:
            df = pd.read_csv(data_path)
            fig = px.line(df, x=x_col, y=y_col, title="左侧折线图")
            # 仅更新左列的Session State
            st.session_state.left_config.update({
                "data_path": data_path,
                "x_col": x_col,
                "y_col": y_col,
                "fig": fig
            })
        except Exception as e:
            st.error(f"生成失败:{str(e)}")
    
    # 条件渲染:仅当左列有已生成的图表时才显示
    if st.session_state.left_config["fig"] is not None:
        st.plotly_chart(st.session_state.left_config["fig"], use_container_width=True)

# 右列操作区(逻辑与左列完全独立)
with col2:
    st.subheader("右侧数据集")
    with st.form(key="right_form"):
        data_path = st.text_input("输入数据集路径", value=st.session_state.right_config["data_path"])
        x_col = st.text_input("X轴列名", value=st.session_state.right_config["x_col"])
        y_col = st.text_input("Y轴列名", value=st.session_state.right_config["y_col"])
        submit_right = st.form_submit_button("生成折线图")
    
    if submit_right:
        try:
            df = pd.read_csv(data_path)
            fig = px.line(df, x=x_col, y=y_col, title="右侧折线图")
            st.session_state.right_config.update({
                "data_path": data_path,
                "x_col": x_col,
                "y_col": y_col,
                "fig": fig
            })
        except Exception as e:
            st.error(f"生成失败:{str(e)}")
    
    if st.session_state.right_config["fig"] is not None:
        st.plotly_chart(st.session_state.right_config["fig"], use_container_width=True)

关键要点说明

  • 状态完全隔离:用left_config和right_config两个独立字典存储各自的参数与图表,操作一侧时绝对不会覆盖另一侧的已保存状态。
  • 避免空状态报错:只有当对应列的图表对象fig不为空时才渲染图表,彻底解决未配置参数时的报错问题。
  • 表单输入回显:输入框默认值绑定到对应列的Session State,提交后再次打开表单能保留之前的配置。
  • 异常友好处理:添加try-except块捕获数据加载、图表生成的异常,给用户明确的错误提示。

内容的提问来源于stack exchange,提问作者Jamalan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 22:20:29