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

如何在Streamlit中实现两个按钮水平紧密并排?

在Streamlit中实现按钮紧密并排的解决方案

你遇到的问题是Streamlit组件默认布局规则导致的,先分析两次尝试的问题,再给出可行方案:

为什么之前的尝试失败

  • 尝试1:Streamlit的每个组件(如st.download_button、st.button)都会生成独立的块级容器,外层的inline-block div无法覆盖组件自身的布局规则,因此按钮依然会换行显示。
  • 尝试2:columns([0.5, 0.5])让每列占据页面50%宽度,即使设置gap="small",按钮仅占列内部分空间,列的空白区域会让按钮间距显得过大。

方案1:自定义CSS + Flex容器(推荐)

通过自定义CSS修改组件默认样式,结合flex容器精准控制按钮间距:

# 注入自定义样式,消除组件默认间距并设置flex布局
st.markdown("""
<style>
/* 让按钮组件容器变为行内块,消除默认外边距 */
.stButton, .stDownloadButton {
    display: inline-block;
    margin: 0;
}
/* Flex容器,控制按钮间距 */
.button-group {
    display: flex;
    gap: 6px; /* 可自定义按钮间距,设为0则完全紧密 */
    align-items: center;
}
</style>
""", unsafe_allow_html=True)

# 用Flex容器包裹两个按钮
st.markdown('<div class="button-group">', unsafe_allow_html=True)

# 下载按钮
st.download_button(
    label="Download data as CSV",
    data=filtered_data.to_csv().encode('utf-8'),
    file_name='filtered_data.csv',
    mime='text/csv',
    key="download_csv"
)

# 重置按钮
if st.button("Reset Metrics", key="reset_metrics"):
    st.experimental_rerun()

st.markdown('</div>', unsafe_allow_html=True)

方案2:优化Columns配置(无需CSS)

调整列宽比例和间距,让列的宽度适配按钮内容:

# 按按钮文本长度设置列宽比例,gap设为none消除列间距
col1, col2 = st.columns([0.3, 0.2], gap="none")

with col1:
    st.download_button(
        label="Download data as CSV",
        data=filtered_data.to_csv().encode('utf-8'),
        file_name='filtered_data.csv',
        mime='text/csv',
        key="download_csv"
    )

with col2:
    if st.button("Reset Metrics", key="reset_metrics"):
        st.experimental_rerun()

你可以根据按钮的实际文本长度调整[0.3, 0.2]的比例,让列宽刚好包裹按钮。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 13:25:31