Button clicking inside a for loop can not differentiate which button was clicked

Here is the code for which shows LLMs output on buttons which is generated in json format and I want to click on one button and send its response to save_option function but without clicking it is sending all button data to that function.

result = json.loads(result)
for sen in result[‘ad_options’]:
st.button(sen[‘scenario’], key=None, on_click=save_option(sen[‘scenario’]))

result value:

def save_option(option_label):
print(“‘Here it should print’”, option_label)

output :

You should set a unique key for each button.

import streamlit as st
import json

def save_option(scenario):
    st.session_state.scenario = scenario

result = json.loads('{"ad_options": [{"scenario": "test1"}, {"scenario": "test2"}, {"scenario": "test3"}]}')
for sen in result['ad_options']:
    st.button(sen['scenario'], key=sen['scenario'], on_click=save_option, kwargs={'scenario': sen['scenario']})

if 'scenario' in st.session_state:
    st.write(f'scenario: {st.session_state.scenario}')
1 Like

Thank You @lkdd-ao for sharing this.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.