gpt4 book ai didi

python - 如何在 streamlit 中添加提交按钮(按钮内的按钮似乎重置了整个应用程序。为什么?)

转载 作者:行者123 更新时间:2023-12-05 05:01:20 36 4
gpt4 key购买 nike

当我点击回答按钮时,它刷新了整个应用。请查看此链接以了解我所期待的 https://youtu.be/WO2mK1VnlZU .只需从此链接(改编自 https://gist.github.com/tvst/036da038ab3e999a64497f42de966a92 93)下载 SessionState.py 文件以导入 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]: /image/IowEQ.png

最佳答案

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

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

关于python - 如何在 streamlit 中添加提交按钮(按钮内的按钮似乎重置了整个应用程序。为什么?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62750900/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com