Reset/delete widgets state on selection of another one

Been using Streamlit for a few days now and created a page hosted locally.

I am struggling with figuring out and understanding session states.

This is an basic example of my app with where the problem is happening.

import streamlit as st
from streamlit_card import card
import base64

with open('transparent.png', "rb") as f:
    data = f.read()
    encoded = base64.b64encode(data)
data = "data:image/png;base64," + encoded.decode("utf-8")


hasClicked = card(
  title="Button 1",
  text="Some description",
  image=data,
  on_click=lambda: print('hi'),
  key='first'
)

hasClicked2 = card(
  title="Button 2",
  text="Some description",
  image=data,
  on_click=lambda: print('hi again'),
  key='second'
)

When clicking on the card with key ‘first’ it prints ‘hi’. Which is what I intend. Afterwards though if I click on the card with key ‘second’ it will run as if I clicked the first and second card printing ‘hi’ \n ‘hi again’. When I would like it to just print ‘hi again’ if I select the second card.

It seems once either card is pressed then whenever another card is pressed all cards that previously were pressed get ran again.

Is there a way to reset or delete the state of the cards after they are pressed and perform their action?

Hi @zimmer44

It seems you’re using callback function in your code snippet. I’ve refactored the code to add actual buttons that users can click. And depending on which one was clicked, the corresponding card will be displayed. For example, clicking on button 1 displays card 1 and clicking on button 2 displays card 2.

Here’s the code snippet:

with open('bg-img.png', "rb") as f:
    data = f.read()
    encoded = base64.b64encode(data)

data = "data:image/png;base64," + encoded.decode("utf-8")

def card1():
    return card(
      title="Button 1",
      text="Some description",
      image=data,
      key='first'
    )

def card2():
    return card(
      title="Button 2",
      text="Some description",
      image=data,
      key='second'
    )

st.button('Button 1', on_click=card1)
st.button('Button 2', on_click=card2)

This gives the following:
Screen Recording 2566-12-09 at 15_scaling-0.5_fps-20_speed-7.05_duration-0-13

Hope this helps!

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