Streamlit中根据所选州联动过滤县下拉框异常问题
问题原因与修复方案
你的代码问题出在每次交互都会重新读取CSV文件,加上Streamlit默认的组件状态管理逻辑,导致县下拉框无法正确跟随选中的州更新。另外,重复读取数据也会拖慢应用性能。
修复后的代码
import streamlit as st import pandas as pd # 缓存数据,避免每次交互重复读取CSV @st.cache_data def load_state_county_data(): return pd.read_csv("https://raw.githubusercontent.com/kjhealy/us-county/master/data/census/fips-by-state.csv", encoding='unicode_escape') st.sidebar.info('### ***US States and Counties***') with st.sidebar: state_county_data = load_state_county_data() # 生成州选项列表 states = sorted(state_county_data["state"].unique()) selected_state = st.selectbox("Select a state", states) # 根据选中的州过滤对应县 counties = sorted(state_county_data.loc[state_county_data["state"] == selected_state]["name"].unique()) # 给县下拉框设置唯一key,确保州切换时组件重新渲染 selected_county = st.selectbox("Select a county", counties, key=f"county_{selected_state}") # 实时显示选中结果(不需要点击按钮也能更新) st.write(f"当前选择: {selected_state} - {selected_county}")
关键修复点
- 缓存数据加载:用
@st.cache_data装饰数据加载函数,CSV只会被读取一次,后续交互直接用缓存数据,避免状态混乱。 - 唯一组件Key:给县下拉框设置带州名的key,当选中的州变化时,Streamlit会识别为新组件,重新渲染对应的县选项列表,彻底解决选项不更新的问题。
如果你坚持要保留Update按钮,只需要把实时显示的代码替换成按钮触发的逻辑即可:
if st.button('Update'): st.write(f"Selected: {selected_state} - {selected_county}")
内容的提问来源于stack exchange,提问作者user3646519
相关产品推荐
相关产品推荐

