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

如何修改Streamlit中selectbox下拉框的列宽度以显示完整长文本?

解决方案

方案1:调整侧边栏整体宽度(推荐)

selectbox默认宽度继承父容器(侧边栏)的宽度,你可以在代码开头注入自定义CSS修改侧边栏默认宽度,示例代码如下:

import streamlit as st
import subprocess

# 注入自定义CSS调整侧边栏宽度,可根据实际需要调整350px的数值
st.markdown("""
<style>
    [data-testid="stSidebar"] {
        min-width: 350px;
        max-width: 350px;
    }
</style>
""", unsafe_allow_html=True)

git_output = subprocess.run(['git', 'branch', '-a'], cwd='/home/demo', capture_output=True, text=True).stdout

br_list = git_output.split('\n')

select = st.sidebar.selectbox('Option', list(filter(lambda k: 'remotes/origin' in k and '1v' in k, br_list)))

你可以根据选项实际长度调整min-width和max-width的像素值,60字符的场景下设置350-400px基本可以完整显示全部内容。

方案2:仅调整单个selectbox的宽度

如果你不想修改整个侧边栏的宽度,只想调整这一个selectbox的宽度,可以用如下CSS注入代码:

st.markdown("""
<style>
    [data-testid="stSidebar"] .stSelectbox {
        width: 350px;
    }
</style>
""", unsafe_allow_html=True)

备选优化方案

如果不想调整界面宽度,你可以自定义显示的选项文本,将长文本截断后显示,实际取值还是完整的分支名,示例如下:

# 预处理分支列表,生成(显示文本, 完整值)的元组列表
branch_options = []
for br in filter(lambda k: 'remotes/origin' in k and '1v' in k, br_list):
    # 显示文本截断为30字符加省略号,可根据需要调整长度
    display_text = br if len(br) <=30 else br[:27] + "..."
    branch_options.append( (display_text, br) )

# selectbox通过format_func指定显示文本,实际取值还是完整分支名
select = st.sidebar.selectbox(
    'Option', 
    options=[br[1] for br in branch_options],
    format_func=lambda x: next(br[0] for br in branch_options if br[1] == x)
)

内容的提问来源于stack exchange,提问作者A. Man

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:15:06