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

Streamlit selectbox切换触发整页刷新,如何修改代码避免?

Excel列选择器避免整页刷新的解决方案

问题背景

开发Streamlit Excel分析应用时,通过月份/年份选择并加载Excel文件后,切换列选择器(selectbox)会触发整页刷新,导致已加载的数据丢失,需要重新点击按钮加载,严重影响体验。原应用代码如下:

import streamlit as st
import pandas as pd
import helpers.script as script
    

@st.cache_data  # Cache the function based on month and year
def get_excel_path(month, year):
    return script.get_data(month, year)  # Call the original function

def read_excel_file(uploaded_file):
    """Reads the uploaded CSV file and returns a pandas DataFrame."""
    try:
        df = pd.read_excel(uploaded_file)
        return df
    except Exception as e:
        st.error(f"Error reading the file: {e}")
        return None

def display_unique_values(df, selected_column):
    """Displays the unique values in the selected column."""
    if selected_column:
        unique_values = df[selected_column].unique()
        st.write(f"Unique values in '{selected_column}':")
        st.dataframe(unique_values)


st.title("Excel File Analyzer")

year = st.number_input("Enter Year:", min_value=2024, max_value=None)
month = st.number_input("Enter Month (1-12)", min_value=1, max_value=12, step=1)

excel_path = None
df = None

if st.button("Generate Report"):
    excel_path = get_excel_path(month, year)

if excel_path is not None:
    df = read_excel_file(excel_path)    

if df is not None:
    # Get all column names
    column_options = list(df.columns)

    # Create a selectbox
    selected_column = st.selectbox("Select a column:", column_options, key="column_selectbox")

    display_unique_values(df.copy(), selected_column)  # Avoid modifying original DataFrame

st.stop()

问题原因

Streamlit默认每次用户交互都会重新运行整个脚本,原代码中excel_path和df是局部变量,页面刷新时会被重置为None,导致需要重新点击按钮加载数据。而测试用的file_uploader组件会自动将上传状态存入Streamlit的会话状态,因此不会出现这个问题。

修改方案

使用st.session_state持久化excel_path和df的状态,确保页面刷新时不会丢失已加载的数据。修改后的完整代码如下:

import streamlit as st
import pandas as pd
import helpers.script as script
    

@st.cache_data  # Cache the function based on month and year
def get_excel_path(month, year):
    return script.get_data(month, year)  # Call the original function

def read_excel_file(uploaded_file):
    """Reads the uploaded CSV file and returns a pandas DataFrame."""
    try:
        df = pd.read_excel(uploaded_file)
        return df
    except Exception as e:
        st.error(f"Error reading the file: {e}")
        return None

def display_unique_values(df, selected_column):
    """Displays the unique values in the selected column."""
    if selected_column:
        unique_values = df[selected_column].unique()
        st.write(f"Unique values in '{selected_column}':")
        st.dataframe(unique_values)


st.title("Excel File Analyzer")

# 初始化会话状态变量
if 'excel_path' not in st.session_state:
    st.session_state.excel_path = None
if 'df' not in st.session_state:
    st.session_state.df = None

year = st.number_input("Enter Year:", min_value=2024, max_value=None)
month = st.number_input("Enter Month (1-12)", min_value=1, max_value=12, step=1)

if st.button("Generate Report"):
    st.session_state.excel_path = get_excel_path(month, year)
    # 读取文件并存入会话状态
    st.session_state.df = read_excel_file(st.session_state.excel_path)

# 从会话状态获取数据
df = st.session_state.df

if df is not None:
    # Get all column names
    column_options = list(df.columns)

    # Create a selectbox
    selected_column = st.selectbox("Select a column:", column_options, key="column_selectbox")

    display_unique_values(df.copy(), selected_column)  # Avoid modifying original DataFrame

st.stop()

关键修改点

  • 初始化st.session_state存储excel_path和df,确保页面刷新时数据不会丢失
  • 点击"Generate Report"按钮时,将获取的文件路径和读取的DataFrame存入会话状态
  • 后续直接从会话状态读取df,避免每次交互都重新加载文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 07:20:07