如何在 Streamlit 中设置按钮样式

bor*_*hev 4 css styling streamlit

我的应用程序中有一个按钮,我想在用户单击它时对其进行样式设置。问题是,因为 Streamlit 不允许我们向我们创建的对象发出类,所以我需要找到一种方法以稳健且与版本无关的方式指定确切的按钮。这是按钮在 Streamlit 中的样子:

<div class="row-widget stButton" style="width: 64px;"><button kind="primary" class="css-4eonon edgvbvh1"></button></div>
Run Code Online (Sandbox Code Playgroud)

bor*_*hev 6

我想出的唯一解决方案是使用一组唯一的元素定义行。这有点像黑客,但效果很好,并且是一种解决方案,直到 Streamlit 社区提出更好的方法。

\n

在此示例中,我将有一行 4 列,这对于我的侧边栏来说是唯一的。

\n
col1, col2, col3, col4 = st.sidebar.columns([1, 1, 1, 1])\n
Run Code Online (Sandbox Code Playgroud)\n

按钮:

\n
with col1:\n    st.button("", on_click=style_button_row, kwargs={\n        \'clicked_button_ix\': 1, \'n_buttons\': 4\n    })\nwith col2:\n    st.button("", on_click=style_button_row, kwargs={\n        \'clicked_button_ix\': 2, \'n_buttons\': 4\n    })\nwith col3:\n    st.button("\xe2\x97\x80", on_click=style_button_row, kwargs={\n       \'clicked_button_ix\': 3, \'n_buttons\': 4\n\n    })\nwith col4:\n    st.button("", on_click=style_button_row, kwargs={\n        \'clicked_button_ix\': 4, \'n_buttons\': 4\n    })\n\n
Run Code Online (Sandbox Code Playgroud)\n

样式方式灵感来自Can CSS detector of child an element has?

\n
div[data-testid*="stHorizontalBlock"] > div:nth-child(%(nth_child)s):nth-last-child(%(nth_last_child)s) button\n
Run Code Online (Sandbox Code Playgroud)\n

造型功能:

\n
def style_button_row(clicked_button_ix, n_buttons):\n    def get_button_indices(button_ix):\n        return {\n            \'nth_child\': button_ix,\n            \'nth_last_child\': n_buttons - button_ix + 1\n        }\n\n    clicked_style = """\n    div[data-testid*="stHorizontalBlock"] > div:nth-child(%(nth_child)s):nth-last-child(%(nth_last_child)s) button {\n        border-color: rgb(255, 75, 75);\n        color: rgb(255, 75, 75);\n        box-shadow: rgba(255, 75, 75, 0.5) 0px 0px 0px 0.2rem;\n        outline: currentcolor none medium;\n    }\n    """\n    unclicked_style = """\n    div[data-testid*="stHorizontalBlock"] > div:nth-child(%(nth_child)s):nth-last-child(%(nth_last_child)s) button {\n        pointer-events: none;\n        cursor: not-allowed;\n        opacity: 0.65;\n        filter: alpha(opacity=65);\n        -webkit-box-shadow: none;\n        box-shadow: none;\n    }\n    """\n    style = ""\n    for ix in range(n_buttons):\n        ix += 1\n        if ix == clicked_button_ix:\n            style += clicked_style % get_button_indices(ix)\n        else:\n            style += unclicked_style % get_button_indices(ix)\n    st.markdown(f"<style>{style}</style>", unsafe_allow_html=True)\n
Run Code Online (Sandbox Code Playgroud)\n

结果:\n在此输入图像描述

\n