I’m encountering an issue with coloring buttons in Streamlit and seeking guidance on how to achieve this. I’m attempting to create two buttons with different background colors, one green and the other red, using Streamlit’s st.button.
Here’s the code snippet I’ve tried:
# Define custom CSS for button colors
button1_color = "#00FF00" # Green color for Button 1
button2_color = "#FF0000" # Red color for Button 2
# Create buttons with st.button
button1_clicked = st.button("Button 1", key="button1")
button2_clicked = st.button("Button 2", key="button2")
# Check button states and print messages
if st.button("Submit"):
if button1_clicked:
st.write("Button 1 pressed")
elif button2_clicked:
st.write("Button 2 pressed")
# Apply CSS to modify button appearance
button_style = f"""
<style>
div[data-baseweb="button"] div:nth-child(1) button {{
background-color: {button1_color} !important;
color: white !important;
}}
div[data-baseweb="button"] div:nth-child(2) button {{
background-color: {button2_color} !important;
color: white !important;
}}
</style>
"""
st.markdown(button_style, unsafe_allow_html=True)
However, the button colors don’t seem to change as intended. I’ve attempted to use CSS styling to modify the buttons’ appearance, but it doesn’t reflect the specified colors.
Is there a better approach or a different way to set button colors in Streamlit? Any insights or guidance would be greatly appreciated.
Your form button should be in a form and you’ll still need to refer to the HTML element “button.” The stylable container can’t natively identify Streamlit elements by their (Streamlit function) names. The CS needs to be targeted to the underlying HTML (which you can get to by inspecting elements.)
Try this:
import streamlit as st
from streamlit_extras.stylable_container import stylable_container
# Create buttons with st.button
with stylable_container(
"green",
css_styles="""
button {
background-color: #2E8B57;
color: #F5F5F5
}""",
):
f = st.form("my_form")
if f.form_submit_button(label="Place"):
st.write("Place pressed")