Home > Mobile >  Maintaining the display of a dataframe in Streamlit
Maintaining the display of a dataframe in Streamlit

Time:06-07

I have a problem, I use buttons to make some computing and displaying dataframes, I press the first button to display my first dataframe and when I press the second button, my second dataframe is shown but my first disappears. I want to maintain the display of my first dataframe (and all those before).... A code example :

import streamlit as st
import pandas as pd

st.subheader("Test")

df_first = pd.DataFrame({"col1": [1, 2, 3, 1, 2, 3], "col2": [4, 5, 6, 4, 5, 6]})
df_second = pd.DataFrame({"col1": [100, 200, 300], "col2": ["www.google.com", "www.facebook.com", "www.youtube.com"]})

button_first = st.button("Display first")
if button_first :
    st.write(df_first)

button_second = st.button("Display second")
if button_second:
    st.write(df_second)

Anybody know how to proceed ? Thanks !

CodePudding user response:

The concept of streamlit is to run the script from top to bottom when there is a user interaction with widget. So when you first press the first button it will rerun from top to bottom and show the first frame. But when you press the second button, it will rerun from top to bottom again and will not show the first frame but will show the second frame.

You can use st.checkbox() to get your desired behavior because a checkbox once checked is always checked and the first frame will always be shown when you press the second button.

You can also use a session state and callback.

import streamlit as st
import pandas as pd


if 'button_1' not in st.session_state:
    st.session_state.button_1 = False
if 'button_2' not in st.session_state:
    st.session_state.button_2 = False


def cb1():
    st.session_state.button_1 = True
def cb2():
    st.session_state.button_2 = True


st.subheader("Test")

df_first = pd.DataFrame({"col1": [1, 2, 3, 1, 2, 3], "col2": [4, 5, 6, 4, 5, 6]})
df_second = pd.DataFrame({"col1": [100, 200, 300], "col2": ["www.google.com", "www.facebook.com", "www.youtube.com"]})

st.button("Display first", on_click=cb1)
if st.session_state.button_1:
    st.write(df_first)

st.button("Display second", on_click=cb2)
if st.session_state.button_2:
    st.write(df_second)
  • Related