Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add submit button in streamlit (The button inside a button seems to reset the whole app.Why?)

when i click answer button it refreshing whole app. please see this link for what i am exactly expecting https://youtu.be/WO2mK1VnlZU. just download SessionState.py file from this link(adapted from https://gist.github.com/tvst/036da038ab3e999a64497f42de966a92 93) to import SessionState Thanks in advance

import streamlit as st
import SessionState
import random
import operator



def random_problem():
    st.markdown("<h1 style = 'text-align:center; color:green;'>Simple Math</h1>", unsafe_allow_html=True)
    
    session_state = SessionState.get(name = "", button_start = False)
    
    session_state.name = st.text_input("Enter Your Name")
    
    button_start = st.button('Start Game')
    if button_start:
        session_state.button_start = True
    if session_state.button_start:
        st.write("Welcome ", session_state.name)
        session_state.operators = {
            '+': operator.add,
            '-': operator.sub,
            '*': operator.mul,
            '/': operator.truediv,
            }
        session_state.num1 = random.randint(1,10)
        
        session_state.num2 = random.randint(1,10)
        
        session_state.operation = random.choice(list(session_state.operators.keys()))
        session_state.answer = session_state.operators.get(session_state.operation)(session_state.num1,session_state.num2)
        st.write('What is:', session_state.num1, session_state.operation, session_state.num2,'?')
        session_state.ans = st.text_input('Answer: ')
        session_state.button_submit = st.button('Answer')
        if session_state.button_submit:
            if session_state.answer == session_state.ans:
                st.write('Correct')
            else:
                st.write('Incorrect')
    
random_problem()

```[![when i click answer button it keep on refreshing whole app][1]][1]


  [1]: https://i.sstatic.net/IowEQ.png
like image 978
Suneel Kumar Avatar asked Sep 06 '25 00:09

Suneel Kumar


2 Answers

That`s how streamlit works - every time you change your choice (for example click on a button) it runs the whole script again.

But - you can use caching in order to cache things that you have to calculate again and again. Please read here about caching in streamlit - https://docs.streamlit.io/en/stable/caching.html

like image 93
theletz Avatar answered Sep 08 '25 14:09

theletz


For future references, Streamlit now have forms which will wait to run the codes until form submit button is pressed.

with st.form("key1"):
    # ask for input
    button_check = st.form_submit_button("Button to Click")

# do something to calculate. Will not run until button is clicked.

See the blog post by Streamlit. https://blog.streamlit.io/introducing-submit-button-and-forms/

like image 28
user3243944 Avatar answered Sep 08 '25 13:09

user3243944