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

如何仅用Python调整Streamlit按钮大小与Expander高度?

纯Python代码调整Streamlit中Expander与按钮的垂直对齐

以下几种纯Python方案可以解决Expander和按钮视觉不协调的问题,无需使用CSS:

方法1:增加按钮内换行符拉高按钮高度

直接在按钮标签里添加更多换行,让按钮高度匹配Expander的标题栏:

instructionCol, buttonCol = st.columns([4,1])
with instructionCol:
    with st.expander("Instructions"):
        st.write("Pretend these are the instructions.")
with buttonCol:
    # 多添加换行符增大按钮高度
    st.button("\n\nRestart\n\n", on_click=board.reset)

方法2:用占位空行撑高按钮列

在按钮上下添加空文本,让按钮所在列的整体高度和Expander对齐,同时让按钮垂直居中:

instructionCol, buttonCol = st.columns([4,1])
with instructionCol:
    with st.expander("Instructions"):
        st.write("Pretend these are the instructions.")
with buttonCol:
    # 上方占位空行
    st.write("")
    st.button("\nRestart\n", on_click=board.reset)
    # 下方占位空行
    st.write("")

方法3:垂直子列布局控制按钮位置

在按钮列内创建垂直方向的子列,让按钮位于中间区域,匹配Expander的高度:

instructionCol, buttonCol = st.columns([4,1])
with instructionCol:
    with st.expander("Instructions"):
        st.write("Pretend these are the instructions.")
with buttonCol:
    # 垂直三分列,按钮放在中间列
    top, mid, bottom = st.columns([1,2,1])
    with mid:
        st.button("\nRestart\n", on_click=board.reset)

这些方案都基于Streamlit原生Python API实现,你可以根据实际显示效果调整换行数量或子列的比例,直到视觉协调为止。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 13:52:22