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
})
受 CSS启发的样式方式可以检测元素的子元素数量吗?:
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 - 如何获取包含类名的选择器
- python - 我怎样才能总是在列周围完美地安装一个 ttk 窗口?
- python - Scrapy在mongodb [pymongo]中保存重复文档,如何防止重复文档
- c - 一个函数的返回值正常工作,第二个函数的返回值不反映正确的值
- python - 如何更改仅一个子图周围的颜色?
- azure - 使用 Azure 服务总线实现扇出模式的最佳方式
- c++ - 递归函数错误:“-var-create:无法创建变量对象”
- java - 如何编写测试用例?
- javascript - 在角度 AoT 编译器中导出变量
- python - 通过 boto3 担任 IAM 用户角色时访问被拒绝