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

Streamlit Pills组件selection_mode参数失效问题求助

解决Streamlit Pills多选功能失效问题

问题根源

  • 原生Streamlit没有内置st.pills()组件,直接调用会抛出AttributeError,必须依赖第三方组件库。
  • 常规的streamlit-pills库不支持多选模式,selection_mode="multi"不是它的合法参数,设置后不会生效。
  • streamlit-pills-multiselect包可能存在版本冲突或使用方式错误,导致多选功能未正常启用。

有效解决方案

方案1:使用支持多选的第三方Pills组件

先卸载可能冲突的旧包,再安装支持多选的版本:

pip uninstall -y streamlit-pills streamlit-pills-multiselect
pip install streamlit-pills-multiselect

按以下正确方式调用组件:

import streamlit as st
from streamlit_pills import pills

selected = pills(
    label="请选择选项",
    options=["选项1", "选项2", "选项3"],
    selection_mode="multi",
    default=["选项1"]  # 可选:设置默认选中项
)

st.write("你选中的选项:", selected)

方案2:用原生组件模拟Pills多选效果

如果第三方组件仍有问题,可通过原生st.checkbox配合自定义CSS实现Pills样式的多选:

import streamlit as st

# 自定义CSS将复选框转为Pills样式
st.markdown("""
<style>
div.stCheckbox > label {
    padding: 8px 16px;
    border-radius: 20px;
    background-color: #f0f2f6;
    margin-right: 8px;
    cursor: pointer;
}
div.stCheckbox > label:hover {
    background-color: #e0e5eb;
}
div.stCheckbox > input:checked + label {
    background-color: #007bff;
    color: white;
}
</style>
""", unsafe_allow_html=True)

# 创建横向排列的多选选项
options = ["选项1", "选项2", "选项3"]
selected = []
cols = st.columns(len(options))
for idx, opt in enumerate(options):
    with cols[idx]:
        if st.checkbox(opt, key=f"pill_{idx}"):
            selected.append(opt)

st.write("你选中的选项:", selected)

注意事项

  • 确保Streamlit版本在1.20以上,避免组件兼容问题。
  • 使用自定义CSS时,若Streamlit版本更新导致样式失效,需调整CSS选择器适配新的页面结构。

内容的提问来源于stack exchange,提问作者D Jay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 09:03:12