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

如何实现Streamlit按钮点击时保留旧表单并生成新表单?

解决Streamlit点击按钮保留旧表单并新增表单的问题

Streamlit每次交互都会重新运行整个脚本,所以要靠st.session_state持久化已添加的表单记录,这样每次重新运行时能渲染所有历史表单。以下是具体实现方案:

修改后的完整代码

import streamlit as st

def AddLayer(layer_type, index):
    # 用索引生成唯一表单Key,避免组件冲突
    with st.form(f"form_{index}"):
        st.subheader(f"表单 {index+1} - 类型:{layer_type}")
        if layer_type == "one":
            test = st.number_input("示例数字输入", key=f"num_input_{index}")
            submitted = st.form_submit_button("保存", key=f"submit_{index}")
            if submitted:
                # 持久化每个表单的提交数据
                if "saved_data" not in st.session_state:
                    st.session_state.saved_data = {}
                st.session_state.saved_data[f"form_{index}"] = test
                st.success(f"表单 {index+1} 已保存!输入值:{test}")
        elif layer_type == "two":
            # 类型two的表单逻辑,同样加唯一Key
            text_input = st.text_input("示例文本输入", key=f"text_input_{index}")
            submitted = st.form_submit_button("保存", key=f"submit_two_{index}")
            if submitted:
                st.success(f"表单 {index+1}(类型two)已保存!")
        elif layer_type == "three":
            # 可扩展类型three的表单逻辑
            select_option = st.selectbox("示例下拉选择", ["选项A", "选项B"], key=f"select_{index}")
            submitted = st.form_submit_button("保存", key=f"submit_three_{index}")
            if submitted:
                st.success(f"表单 {index+1}(类型three)已保存!选择:{select_option}")

# 初始化session_state,存储已添加的层类型列表
if "layers" not in st.session_state:
    st.session_state.layers = []

choices = [" ", "one", "two", "three"]
layer = st.selectbox("选择层类型:", choices)

if st.button("添加表单"):
    if layer != " ":  # 跳过空选项
        st.session_state.layers.append(layer)

# 遍历已添加的层,渲染所有表单
for idx, layer_type in enumerate(st.session_state.layers):
    AddLayer(layer_type, idx)

核心逻辑说明

  • 持久化表单记录:用st.session_state.layers保存所有用户选择添加的层类型,每次脚本重新运行时都会遍历这个列表,重新渲染所有已添加的表单,不会丢失旧表单。
  • 唯一组件Key:每个表单、输入框、提交按钮都通过index生成唯一的key参数,避免Streamlit将不同表单的组件识别为同一个,导致渲染异常或数据冲突。
  • 独立提交逻辑:每个表单的提交按钮和数据存储都相互独立,提交后的结果可以存在st.session_state.saved_data中,方便后续调用或展示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 23:30:14