2

当我单击答案按钮时,它会刷新整个应用程序。请参阅此链接了解我所期待的https://youtu.be/WO2mK1VnlZU。只需从此链接下载 SessionState.py 文件(改编自https://gist.github.com/tvst/036da038ab3e999a64497f42de966a92 93)即可导入 SessionState在此先感谢

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.stack.imgur.com/IowEQ.png
4

2 回答 2

0

这就是 streamlit 的工作原理 - 每次您更改选择(例如单击按钮)时,它都会再次运行整个脚本。

但是 - 您可以使用缓存来缓存您必须一次又一次地计算的东西。请在此处阅读有关 streamlit 中的缓存的信息 - https://docs.streamlit.io/en/stable/caching.html

于 2020-07-07T11:17:06.927 回答
-1

对于将来的参考,Streamlit 现在有表单,它将等待运行代码,直到按下表单提交按钮。

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.

请参阅 Streamlit 的博客文章。https://blog.streamlit.io/introducing-submit-button-and-forms/

于 2021-04-30T20:38:40.987 回答