Dynamic Buttons

Hi Streamlit Community!

Day on day while I solve interesting requirements, Its really interesting. I would like to know from the community is such requirement is possible.

Creating Dynamic Buttons: Below code creates as many buttons as the items in the list. But the question is how do I access the individual button clicks here?

import streamlit as st
import random
import string

def get_random_string(length):
    # Random string with the combination of lower and upper case
    letters = string.ascii_letters
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Random string is:", result_str)

applist = ["Sentiment Analysis", "Word Cloud", "Topic Model"]
for i in range(len(applist)):
    app = st.button(applist[i], key=get_random_string(8))

Say, I want to control my application based on the individual button click.

Curious to know if such problems can be solved. Thanks.:slight_smile:

Hi @Chakra,

I am not sure if I understood your question properly but is this something what you are looking for ?

We have 5 buttons based on a range ( can be replaced with a list ),
And you can just save the results in a list and loop over them to see which button was clicked.

import streamlit as st

buttons = []

for i in range(5):

for i, button in enumerate(buttons):
    if button:
        st.write(f"{i} button was clicked")

PS. I think st.radio makes more sense in such case :slight_smile:

1 Like

@ash2shukla Awesome. Great Thanks. I am looking for similar. Can we associate Session State as well to such approach?

@Chakra Sure, as long as its serializable it can be stored in session state :slight_smile:

1 Like

Awesome! Thanks @ash2shukla. Let me start building on top of this dynamic controls. :slight_smile:

1 Like