Suneel Kumar
Suneel Kumar

Reputation: 137

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

Upvotes: 4

Views: 13564

Answers (2)

user3243944
user3243944

Reputation: 121

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/

Upvotes: 2

theletz
theletz

Reputation: 1805

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

Upvotes: 2

Related Questions