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

Streamlit美国州城联动下拉框问题:字典显示异常

解决Streamlit中美州-城市联动下拉框的显示与匹配问题

核心问题修正点

当前代码用states_dict.items()作为州下拉框选项,导致显示(州全名, 州缩写)的键值对,需调整为仅显示州全名,同时保留全名到缩写的映射用于城市筛选;另外回调函数调用方式有误,城市列表初始化逻辑也需优化避免重复追加数据。

修改后的完整代码

import streamlit as st
import geonamescache

col1, col2, col3 = st.columns(3)

with col2:
    gc = geonamescache.GeonamesCache()
    cities = gc.get_cities()
    us_states = gc.get_us_states()

    # 初始化session状态
    if "disabled" not in st.session_state:
        st.session_state.disabled = True

    def callback():
        st.session_state.disabled = False

    # --- 处理州数据:建立州全名到缩写的映射,生成仅含全名的选项列表 ---
    state_name_to_code = {code['name']: state for state, code in us_states.items()}
    state_options = ["Select a State"] + list(state_name_to_code.keys())

    # 州下拉选择框:仅显示州全名
    selected_state_name = st.selectbox("Select a State", state_options)

    if selected_state_name != "Select a State":
        st.write("You selected:", selected_state_name)
        # 获取选中州的缩写
        selected_state_code = state_name_to_code[selected_state_name]
    else:
        st.write("#")
        selected_state_code = None

    # --- 处理城市数据:根据选中州的缩写筛选 ---
    city_options = ["Select a city"]
    if selected_state_code:
        for city in cities.values():
            if city['countrycode'] == 'US' and city['admin1code'] == selected_state_code:
                city_options.append(city['name'])

    # 城市下拉选择框:仅当选中州后启用
    selected_city = st.selectbox(
        "Select a city", 
        city_options, 
        disabled=st.session_state.disabled, 
        on_change=callback  # 传入函数名而非直接调用
    )

    if selected_city != "Select a city":
        st.write("You selected:", selected_city)
    else:
        st.write("#")

关键改动说明

  • 州数据处理:
    • 构建state_name_to_code字典,实现州全名到缩写的快速映射
    • 生成state_options列表,默认选项加所有州全名,确保下拉框仅显示州全名
  • 城市筛选逻辑:
    • 将城市列表初始化移到州选择之后,每次选州都重新生成对应城市列表,避免重复追加旧数据
    • 仅在选中有效州时,用对应缩写筛选美国城市
  • 回调函数修正:
    • on_change参数传入函数名callback而非callback(),后者会直接执行函数,前者才是触发选择变化时调用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 20:12:28