Assign different part of codes to st.button in streamlit app

Question:

I am building an streamlit app, I defined 3 buttons.
I have a large set of codes that does different things. If a user choose button1, it does something, if a user choose button2 it should perform other part of code and does something else.

There is two issue I am dealing with:

1- when I select button2, and then I select slider, or change the option in st.sidebar.checkbox, which are defined inside this if, it doesn’t do anything.

2- how to define data frame under buttom2 which can be called under button 3 as well?

3- if I define slider and st.sidebar.checkbox outside of the if button2, the problem of 1 will be solved but what is outside of if button2, will be shown also in if button1.

Can you help me to develop this code further?

import streamlit as st

col1, col2, col3 = st.columns([.4,.5,1])

m = st.markdown("""
<style>
div.stButton > button:first-child {
    background-color: rgb(0,250,154);
}
</style>""", unsafe_allow_html=True)


with col1:
    button1 = st.button('In')

with col2:
    button2 = st.button('DA')

with col3:
    button3 = st.button('Vi')

if button1:
    write some intro text
if button2:
    a data frame is generated here
    there is slider and st.sidebar.checkbox defined in this part.
if button3:
    use the data frame generated in button2 and plot 
Asked By: user14269252

||

Answers:

You can probably use st.tabs and st.cache_data instead:

import streamlit as st
import pandas as pd

tab1, tab2, tab3 = st.tabs(["In", "Da", "Vi"])


@st.cache_data()
def create_dataframe(slider_val):
    # This pretends it's a long computation..
    import time
    time.sleep(5)
    return pd.DataFrame({"aa": [slider_val]})


def show_dataframe(df):
    st.dataframe(df)


with tab1:
    st.header("In")
    st.image("https://static.streamlit.io/examples/cat.jpg", width=200)

with tab2:
    st.header("DA")

    slider_val = st.slider("Foobar", 0, 30, step=10)
    st.write(f"slider_val: {slider_val}")

    df = create_dataframe(slider_val)

with tab3:
    st.header("Vi")
    show_dataframe(df)

It gives 3 tabs:

enter image description here enter image description here enter image description here


See the st.tabs documentation here: https://docs.streamlit.io/library/api-reference/layout/st.tabs

Answered By: vvvvv
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.