Is it possible to generate multiple individual rows of customized buttons within Streamlit?

I utilized the insights from this post to craft multiple buttons in Streamlit: HOW TO STYLE A BUTTON IN STREAMLIT. The outcome appears as follows: enter image description here The code that I implemented is:

def style_button(click_button_i, nb_buttons):
    def get_button_indices(button_i):
        return {
            'nth_child': button_i,
            'nth_last_child': nb_buttons - button_i + 1
        }

    click_style = """
    div[data-testid*="stHorizontalBlock"] > div:nth-child(%(nth_child)s):nth-last-child(%(nth_last_child)s) button {
        border-color: rgb(50,205,50);
        color: rgb(50,205,50);

        box-shadow: rgba(50,205,50, 0.5) 0px 0px 0px 0.2rem;
        outline: currentcolor none medium;
    }
    """
    unclick_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 i in range(nb_buttons):
        i += 1
        if i == click_button_i:
            style += click_style % get_button_indices(i)
        else:
            style += unclick_style % get_button_indices(i)
    st.markdown(f"<style>{style}</style>", unsafe_allow_html=True)

and:

st.subheader("Is this the correct answer?")
col1, col2= st.columns([1,1])
with col1:
    st.button("YES", on_click=style_button, key= "a",kwargs={
        'click_button_i': 1, 'nb_buttons': 2
    })
with col2:
    st.button("NO", on_click=style_button, key="b",kwargs={
        'click_button_i': 2, 'nb_buttons': 2
    })

st.subheader("Additional content...")

st.subheader("Is this a valid response?")
col1, col2= st.columns([1,1])
with col1:
    st.button("YES", on_click=style_button, key= "c",kwargs={
        'click_button_i': 1, 'nb_buttons': 2
    })
with col2:
    st.button("NO", on_click=style_button, key="d",kwargs={
        'click_button_i': 2, 'nb_buttons': 2
    })

Upon clicking a button (e.g., YES), all other YES buttons are automatically chosen and stay green without individual interaction.

My query pertains to creating multiple rows of independent buttons. Is it feasible?

I experimented with altering the number of buttons in st.button, I tried defining a style_button2, yet it seems that the beacon for st.buttons is consistent across all instances. Perhaps modifications within the nth_child aspect are required, but CSS intricacies escape me.

Thank you for your feedback!

Answer №1

Being new to streamlit, I want to offer some assistance. You can start by utilizing basic CSS button modifications like the ones demonstrated here.

import streamlit as st

click_style = """ 
<style> 
div[data-testid*="stButton"] > button:active {
    border-color: rgb(50,205,50);
    color: rgb(50,205,50);
    box-shadow: rgba(50,205,50, 0.5) 0px 0px 0px 0.2rem;
    outline: currentcolor none medium;
}
div[data-testid*="stButton"] > button{
    pointer-events: none;
    cursor: not-allowed;
    opacity: 0.65;
    filter: alpha(opacity=65);
    -webkit-box-shadow: none;
    box-shadow: none;
}
div[data-testid*="stButton"] > button:visited{
    pointer-events: none;
    cursor: not-allowed;
    opacity: 0.65;
    filter: alpha(opacity=65);
    -webkit-box-shadow: none;
    box-shadow: none;
}
</style>

"""

Furthermore, you don't necessarily need unique identifiers for buttons since each button already has a unique key that can be accessed using st.session_state.key. Although in this instance I have not utilized them, we can incorporate them if needed. The revised code snippet is as follows:

st.markdown(click_style, unsafe_allow_html=True)


st.subheader("Is this the correct answer?")
col1, col2 = st.columns([1, 1])
with col1:
    st.button("YES", key="a")
with col2:
    st.button("NO", key="b")

st.subheader("Additional content here...")

st.subheader("Is this an accurate response?")
col1, col2 = st.columns([1, 1])
with col1:
    st.button("YES", key="c")
with col2:
    st.button("NO", key="d")

If there are any uncertainties, feel free to ask for clarification.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for adding a box shadow beneath my header?

I am currently attempting to add a box shadow under my header, similar to the design featured in the project mockup at https://github.com/RaghavMangrola/the-brighton-times. After trying to implement the following CSS property and value: .header { ...

Utilizing regular expressions in Powershell to modify a CSS file

Snippet from my current theme.css file: .actionBlock[selected] { color: var(--gray11); background-color: var(--gray11); } I am trying to modify color: var(--gray11); to color: #FFF; /* UPDATED : var(--gray11) */ After attempting in Po ...

How can I use jQuery to rotate a DIV to a specific angle?

Similar Question: How to Rotate a Div Element using JavaScript Is there a way to rotate a DIV and its contents by a specific degree in jQuery? I'm looking for a solution that allows me to set the rotation angle to any value, not just fixed angles ...

Locating elements with CSS Selector in Selenium - A complete guide

Currently, my code is set up to access a website and click on each row in the table which then opens a new window. My goal is to extract one specific piece of information from this new window, but I am struggling to utilize CSS selectors to retrieve the f ...

the inline-block display property is not initializing properly

I am facing an issue with positioning two divs next to each other. Initially, using the display: inline-block; property for both divs worked fine. However, as soon as I added a <p> tag into one of the divs, its placement got messed up. Here is the cu ...

Ways to display distinct text boxes based on selected radio button?

Currently, I am working with JSP and have implemented an HTML form that includes a "Process" button at the top. When this button is clicked, it displays a form with two radio buttons - TestClient and TestServer. The form also contains a Submit button. If ...

Vue 3 now allows for disabling the automatic renaming of CSS properties like "top/bottom/left/right" to "inset"

I noticed that Vue (or maybe Vite) automatically changes my css style attributes from "top: 0; right: 0; left: 0; bottom: 0;" to "inset: 0px;" However, this adaptation doesn't work well for older browsers that do not support the i ...

Find the elements of <a> tags specifically without the attribute href

Currently, I am extracting the class of all <a> elements in an HTML document of a webpage using VB.net from a WinForm: Dim htmlLinks As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("a") For Each link As HtmlElement In htmlLi ...

Centered perfectly in a bootstrap card

I'm struggling to create a bootstrap card with a logo perfectly centered, but the logo seems fixed at the top. How can I fix this issue? <div class="col-xl-3 col-md-6"> <div class="card mini-stat"> <div class="card-body tex ...

How come the styles in my CSS file aren't being applied to my images based on their class or ID?

When I apply a className or id to my img tag in my JavaScript (using React.js) and then add a style that references that id or class, the style does not get applied. However, when I do the same for a div, everything works perfectly fine. <--JavaScript- ...

Guide on achieving a full scrollable parent by positioning a pseudo-element absolutely

I am trying to have a position: absolute element fill its parent, even if the parent is scrollable. To demonstrate this issue, I created a codepen example. Although the red overlay fills the div initially, it does not stay overlaid when the content is sc ...

Trouble getting CSS and Javascript to bind when dynamically appending HTML elements

Attempting to dynamically bind HTML from an Angular controller SkillsApp.controller('homeController', function ($scope, $http, $q, $timeout) { $scope.getAllCategories = function () { $http({ url: "/Categories/GetAllCategories", ...

How can custom CSS and JS be loaded in Sencha Touch based on the user's device - PC, tablet, or smartphone?

Is there a way to configure a webpage so that when the user is accessing it from a PC (using Safari/Chrome/Firefox), they see the "normal" version of the page, but if they are using an iPad to view the same URL, they get Sencha Touch (css, js) files in t ...

Is AsciiEffect.js compatible with CSS3DRenderer.js in combination with three.js/WebGL?

Having trouble using the AsciiEffect.js and CSS3DRenderer.js together, wondering if it's possible without tweaking... here's the concept var W = window.innerWidth, H = window.innerHeight; renderer = new THREE.CSS3DRenderer(); effect = new THREE. ...

Is tabIndex being used as a css property?

I'm trying to understand how to utilize the HTML attribute tabindex using CSS. Specifically, I want to assign tabIndex=0 to all div elements that have the className='my-checkbox'. This is my current approach: <div tabIndex="0" classNam ...

Display a popup when a label is clicked, and update the popup contents according to the label chosen

Upon clicking any label in the #nav section, a popup is displayed. However, I want the content inside the popup to change depending on which label is clicked. Currently, the different popup content divs will all hide or show based on CSS only, so I believe ...

Maintain HOVER State in CSS Drop Down Menu upon Clicking

I have implemented a CSS Drop Down Menu on my website. In a specific section of the site, I am using the menu links to trigger AJAX-jQuery calls that dynamically change the content of a DIV without the need for page reloading. <script type="text/javasc ...

Creating an HTML form that resembles StackOverflow's form

I am having an issue with the behavior of my form when inserting multiple tags. I want it to function like the one on this particular website where a scroll bar appears and a new line is created. Is there a way to keep everything on the same row? Check ou ...

Tips for highlighting the final word in the headline using an underline

I'm attempting to create a title style similar to what is shown below https://i.sstatic.net/Qao4g.png The issue I'm facing is achieving the underline effect. I tried using title:after but it didn't give me the exact result I'm looking ...

Cannot modify CSS Position once it has been appended

I have a dilemma where I am appending code from one document to another. After the code is appended, I attempt to set the position of the newly added item using jQuery drag and drop functionality. The positions are stored in an array and then saved in a co ...