Streamlit 如何将多个button按钮放置在同一行展示
Streamlit按钮同行排布实现方案
默认直接连续调用st.button()时,每个按钮会独占一整行宽度,因此会出现分行展示的问题。实现多个按钮同一行排布的核心是使用Streamlit原生的列布局方法st.columns(),不需要引入额外依赖,具体实现如下:
基础实现(等宽按钮)
先创建与按钮数量相等的等宽列,再将按钮分别绑定到对应列中渲染即可:
import streamlit as st # 初始化3个等宽列 col1, col2, col3 = st.columns(3) # 逐列渲染按钮 with col1: st.button("Button 1") with col2: st.button("Button 2") with col3: st.button("Button 3")
自定义宽度/间距
如果需要调整按钮的宽度比例或按钮之间的间距,可以给st.columns()传入自定义宽度列表来实现:
自定义按钮宽度比例
# 三个按钮的宽度比例为2:1:1,可按需修改数值 col1, col2, col3 = st.columns([2, 1, 1]) with col1: st.button("长文本按钮") with col2: st.button("Button 2") with col3: st.button("Button 3")
缩小按钮间距
在按钮列之间插入极小宽度的空列即可压缩间距:
# 0.2宽度的列为占位空列,用来控制按钮间距 col1, gap1, col2, gap2, col3 = st.columns([3, 0.2, 3, 0.2, 3]) with col1: st.button("Button 1") with col2: st.button("Button 2") with col3: st.button("Button 3")
内容的提问来源于stack exchange,提问作者Wing
相关产品推荐
相关产品推荐

