为什么更改streamlit selectbox的值会导致整个页面每次都刷新?

0 投票
1 回答
36 浏览
提问于 2025-04-12 20:53

我正在制作一个Streamlit应用,用来分析Excel文件。在这个应用里,我有一个选择框,用户可以从上传的Excel文件中选择一个列。但是,每次我把选择框的值改成不同的列时,整个页面都会刷新。这种情况我不太想要,因为它会影响用户体验。我该怎么修改代码,才能让选择框的值改变时页面不刷新呢?

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()

补充:我尝试了一个模拟应用,使用了文件上传功能来检查是否正常工作,结果一切都很顺利,而且我用的还是同一个Excel文件的路径,下面是代码。我把这个模拟应用的代码用到主应用里,希望它也能正常工作,但结果并没有。

import streamlit as st
import pandas as pd

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")

uploaded_file = st.file_uploader("Choose an Excel file", type="xlsx")

if uploaded_file is not None:
  df = read_excel_file(uploaded_file)
  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)

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

st.stop()

1 个回答

0

在Streamlit中,每次更新时,它会从头到尾读取所有代码。不过,你可以通过使用缓存来避免这种情况。缓存的作用是检查两个情况。第一个是函数的参数是否相同,第二个是在函数内部的内容是否相同。如果这两者都相同,Streamlit就会跳过执行这个函数。所以最好的办法是对那些不会改变的函数使用缓存。

你可以查看Streamlit中的缓存文档,了解更多信息。这里有个链接给你。

https://docs.streamlit.io/library/advanced-features/caching#advanced-usage

撰写回答