作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的应用程序中有一个按钮,我想在用户单击它时设置它的样式。问题在于,因为 Streamlit 不允许我们向我们创建的对象发布类,所以我需要找到一种方法来以稳健且与版本无关的方式指定确切的按钮。这是按钮在 streamlit 中的样子:
<div class="row-widget stButton" style="width: 64px;"><button kind="primary" class="css-4eonon edgvbvh1">📆</button></div>
最佳答案
我想出的唯一解决方案是用一组唯一的元素定义行。这有点像 hack,但效果很好,并且在 Streamlit 社区想出更好的方法之前是一种解决方案。
在这个例子中,我将有一行有 4 列,这对于我的侧边栏来说是独一无二的。
col1, col2, col3, col4 = st.sidebar.columns([1, 1, 1, 1])
按钮:
with col1:
st.button("📆", on_click=style_button_row, kwargs={
'clicked_button_ix': 1, 'n_buttons': 4
})
with col2:
st.button("👌", on_click=style_button_row, kwargs={
'clicked_button_ix': 2, 'n_buttons': 4
})
with col3:
st.button("◀", on_click=style_button_row, kwargs={
'clicked_button_ix': 3, 'n_buttons': 4
})
with col4:
st.button("🚧", on_click=style_button_row, kwargs={
'clicked_button_ix': 4, 'n_buttons': 4
})
造型方式灵感来自Can CSS detect the number of children an element has? :
div[data-testid*="stHorizontalBlock"] > div:nth-child(%(nth_child)s):nth-last-child(%(nth_last_child)s) button
样式函数:
def style_button_row(clicked_button_ix, n_buttons):
def get_button_indices(button_ix):
return {
'nth_child': button_ix,
'nth_last_child': n_buttons - button_ix + 1
}
clicked_style = """
div[data-testid*="stHorizontalBlock"] > div:nth-child(%(nth_child)s):nth-last-child(%(nth_last_child)s) button {
border-color: rgb(255, 75, 75);
color: rgb(255, 75, 75);
box-shadow: rgba(255, 75, 75, 0.5) 0px 0px 0px 0.2rem;
outline: currentcolor none medium;
}
"""
unclicked_style = """
div[data-testid*="stHorizontalBlock"] > div:nth-child(%(nth_child)s):nth-last-child(%(nth_last_child)s) button {
pointer-events: none;
cursor: not-allowed;
opacity: 0.65;
filter: alpha(opacity=65);
-webkit-box-shadow: none;
box-shadow: none;
}
"""
style = ""
for ix in range(n_buttons):
ix += 1
if ix == clicked_button_ix:
style += clicked_style % get_button_indices(ix)
else:
style += unclicked_style % get_button_indices(ix)
st.markdown(f"<style>{style}</style>", unsafe_allow_html=True)
关于css - 如何在 Streamlit 中设置按钮样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69478972/
我是一名优秀的程序员,十分优秀!