I try to get a bunch of buttons where each one can have to states and the states are shown as text on the button. The states are independent from each other (not nested) but it can happen that two buttons get the same label.
When I try this:
def xbutton(name, label1, label2):
if name not in st.session_state:
st.session_state[name] = False
st.button(label=label1 if st.session_state[name] else label2, key=name, on_click=click_button, args=[name])
def click_button(name):
if st.session_state[name]:
st.session_state[name] = False
else:
st.session_state[name] = True
xbutton('K1', '1', 'X')
xbutton('K2', '6', 'X')
I get an error:
StreamlitValueAssignmentNotAllowedError : Values for the widget with key
‘K1’ cannot be set using st.session_state
.
So it seems that it is not possible to make buttons unique per key.
If I change the code so that I do not set the key:
def xbutton(name, label1, label2):
if name not in st.session_state:
st.session_state[name] = False
st.button(label=label1 if st.session_state[name] else label2, on_click=click_button, args=[name])
def click_button(name):
if st.session_state[name]:
st.session_state[name] = False
else:
st.session_state[name] = True
xbutton('K1', '1', 'X')
xbutton('K2', '6', 'X')
Then I am told to set a unique key.
StreamlitDuplicateElementId: There are multiple button
elements with the same auto-generated ID. When this element is created, it is assigned an internal ID based on the element type and provided parameters. Multiple elements with the same type and parameters will cause this error.
To fix this error, please pass a unique key
argument to the button
element.
But this is not working see first example. Any idea how to fix this?