App Refreshes Before Completion


I’m running on Windows 10 & Anaconda Python 3.7
I’m able to launch the app and it works successfully until the last selectbox where the app refreshes when I pick a value from the selectbox or click on any of the last two buttons. I’m very new to streamlit and would appreciate any help/guidance.

import streamlit as st
import pandas as pd 
import random

def main():
    st.title("Testing Tool")

    #Sample Names
    names = ['Dan','Joe','John','Bob','Scott','Sam']
    # Customer SelectBox
    person_name = st.selectbox("Select Name", names)
    st.write("You selected this:", person_name)

    # Product SelectBox
    products = ['Mars','Snickers','Twix','Kit-kat', 'M&Ms', 'Toblerone','Skittles']
    product = st.selectbox("Select Product", products)
    st.write("You selected this Product:", product)

    # Generate Recommendations
    # Slider
    number_of_recs = st.slider("Number of Recommendations",1,10)
    recs = ''

    if st.button('Click Here'):
        choices_ = ['X','Y','S','A','Z','D']

        recs = random.choices(choices_, k=number_of_recs)
        for p, n in enumerate(recs):
            st.write(f"Rec {p+1}:", n)

        selection = st.selectbox('Select One:', recs, format_func=lambda x: 'Select One' if x == '' else x)
        st.write("You selected:", selection)

        if selection:
            if st.button(f'See Past Purchases for {selection}'):
                st.write('Showing History')

            if st.button(f'See Reviews for {selection}'):
                st.write('Showing Reviews')

        st.write('Click To Generate Recommendations')


Hello @gibranhasan14, welcome to the forum!

Each time you interact with your app, by clicking a button or using the slider, the whole script reruns.
In your case, when you click the Click here button, the app reruns and st.button("Click Here") returns True for this current run only. Next, when you click on the new buttons, you’ll make the whole app rerun again. In consequence, Click Here will return False and everything will be hidden again.

An easy way to fix the issue would be to replace your st.button("Click Here") with a st.checkbox("Generate recommendations").

A second solution, maybe more practical in your situation but needs slightly more work, would be to use session states to keep your values across runs/reloads.