英文:
Streamlit is Repeatedly Running a Loop When Entering Details
问题
我有一个Streamlit代码,最初会要求输入候选人的全名、经验和语言。点击提交按钮后,会显示三个问题(问题1,问题2,问题3)。问题出现在我在问题1的文本框中输入答案后。之后,当我尝试在问题2的文本框中输入答案时,页面会重置并从头开始。我该如何解决这个问题?
以下是代码
import streamlit as st
import pandas as pd
def main():
st.title('Employer Test')
st.markdown('## Candidate Information')
# Full Name Input
full_name = st.text_input('Full Name')
# Experience Dropdown
experience = st.selectbox("Experience", ["Fresher"], index=0)
# Language Dropdown
language = st.selectbox("Language", ["Python"], index=0)
# Button to start the test
if st.button('Submit'):
if full_name:
run_python_test(full_name)
def run_python_test(full_name):
st.title('Python Test')
# Dummy test questions and answers
questions = [
{
'question': 'What is the output of the following code?\n\n```python\nx = 5\nprint(x)\n```',
'options': ['5', '10', '0', 'Error'],
'correct_answer': '5'
},
{
'question': 'Which of the following is a Python data type?',
'options': ['List', 'Streamlit', 'GitHub', 'HTML'],
'correct_answer': 'List'
},
{
'question': 'What is the result of the expression 3 + 7 * 2?',
'options': ['13', '20', '17', 'Error'],
'correct_answer': '17'
}
# Add more questions here...
]
total_questions = len(questions)
score = 0
answer = []
for i, question_data in enumerate(questions):
question = question_data['question']
options = question_data['options']
correct_answer = question_data['correct_answer']
st.write(f'Question {i+1}: {question}')
# Display options for each question
answer.append(st.text_area(f"Enter answer for Question {i+1}", key=f"answer_{i}"))
# Add a submit button
if st.button("Submit Test", key="submit_test"):
# Process the answers and calculate score
for i, ans in enumerate(answer):
if ans == questions[i]['correct_answer']:
score += 1
st.write(f"Question {i+1} Answer: {ans}")
percentage_score = (score / total_questions) * 100
if percentage_score >= 60:
save_result(full_name, percentage_score)
st.session_state['test_completed'] = True
def save_result(full_name, score):
data = {'Full Name': [full_name], 'Score': [score]}
df = pd.DataFrame(data)
df.to_csv('test_results.csv', index=False)
st.write('Result saved successfully!')
if __name__ == '__main__':
main()
英文:
I have a Streamlit code that initially asks for the candidate's Full Name, Experience, and Language. Upon clicking the submit button, it displays three questions (Question 1, Question 2, Question 3). The issue arises when I enter an answer in the text box for Question 1. After that, when I attempt to enter an answer in the text box for Question 2, the page resets and starts from the beginning. How can I resolve this problem?
Here is the code
import streamlit as st
import pandas as pd
def main():
st.title('Employer Test')
st.markdown('## Candidate Information')
# Full Name Input
full_name = st.text_input('Full Name')
# Experience Dropdown
experience = st.selectbox("Experience", ["Fresher"], index=0)
# Language Dropdown
language = st.selectbox("Language", ["Python"], index=0)
# Button to start the test
if st.button('Submit'):
if full_name:
run_python_test(full_name)
def run_python_test(full_name):
st.title('Python Test')
# Dummy test questions and answers
questions = [
{
'question': 'What is the output of the following code?\n\n```python\nx = 5\nprint(x)\n```',
'options': ['5', '10', '0', 'Error'],
'correct_answer': '5'
},
{
'question': 'Which of the following is a Python data type?',
'options': ['List', 'Streamlit', 'GitHub', 'HTML'],
'correct_answer': 'List'
},
{
'question': 'What is the result of the expression 3 + 7 * 2?',
'options': ['13', '20', '17', 'Error'],
'correct_answer': '17'
}
# Add more questions here...
]
total_questions = len(questions)
score = 0
answer = []
for i, question_data in enumerate(questions):
question = question_data['question']
options = question_data['options']
correct_answer = question_data['correct_answer']
st.write(f'Question {i+1}: {question}')
# Display options for each question
answer.append(st.text_area(f"Enter answer for Question {i+1}", key=f"answer_{i}"))
# Add a submit button
if st.button("Submit Test", key="submit_test"):
# Process the answers and calculate score
for i, ans in enumerate(answer):
if ans == questions[i]['correct_answer']:
score += 1
st.write(f"Question {i+1} Answer: {ans}")
percentage_score = (score / total_questions) * 100
if percentage_score >= 60:
save_result(full_name, percentage_score)
st.session_state['test_completed'] = True
def save_result(full_name, score):
data = {'Full Name': [full_name], 'Score': [score]}
df = pd.DataFrame(data)
df.to_csv('test_results.csv', index=False)
st.write('Result saved successfully!')
if __name__ == '__main__':
main()
答案1
得分: 0
似乎你的原始代码中缺少了会话状态,所以已经添加了。
该应用现在允许用户添加他们的姓名和信息,点击提交,然后进行3道问题的测验并提交。之后,他们可以通过一个下载按钮下载测试结果,这在原始代码中是缺失的。
import streamlit as st
import pandas as pd
st.title('雇主测试')
if 'form_submitted' not in st.session_state:
st.session_state['form_submitted'] = False
if 'test_completed' not in st.session_state:
st.session_state['test_completed'] = False
def save_result(full_name, score):
data = {'Full Name': [full_name], 'Score': [score]}
df = pd.DataFrame(data)
df.to_csv('test_results.csv', index=False)
csv = df.to_csv().encode('utf-8')
st.success('结果保存成功!')
st.download_button(
label="下载测试结果",
data=csv,
file_name='test_results.csv',
mime='text/csv',
)
if not st.session_state['form_submitted']:
st.markdown('## 候选人信息')
with st.form(key='candidate_info'):
# 全名输入
full_name = st.text_input('全名')
# 经验下拉菜单
experience = st.selectbox("经验", ["新手"], index=0)
# 语言下拉菜单
language = st.selectbox("语言", ["Python"], index=0)
# 开始测试的按钮
submit_button = st.form_submit_button('提交')
if submit_button:
st.session_state['form_submitted'] = True
st.session_state['full_name'] = full_name
if st.session_state['form_submitted'] and not st.session_state['test_completed']:
st.title('Python 测试')
# 虚拟测试问题和答案
questions = [
{
'question': '以下代码的输出是什么?\n\n```python\nx = 5\nprint(x)\n```',
'options': ['5', '10', '0', '错误'],
'correct_answer': '5'
},
{
'question': '以下哪个是 Python 数据类型?',
'options': ['列表', 'Streamlit', 'GitHub', 'HTML'],
'correct_answer': '列表'
},
{
'question': '表达式 3 + 7 * 2 的结果是什么?',
'options': ['13', '20', '17', '错误'],
'correct_answer': '17'
}
# 在这里添加更多问题...
]
total_questions = len(questions)
score = 0
answer = []
for i, question_data in enumerate(questions):
question = question_data['question']
options = question_data['options']
correct_answer = question_data['correct_answer']
st.write(f'问题 {i+1}: {question}')
# 显示每个问题的选项
answer.append(st.text_area(f"输入问题 {i+1} 的答案", key=f"answer_{i}"))
# 添加一个提交按钮
if st.button("提交测试", key="submit_test"):
# 处理答案并计算得分
for i, ans in enumerate(answer):
if ans == questions[i]['correct_answer']:
score += 1
st.write(f"问题 {i+1} 答案: {ans}")
percentage_score = (score / total_questions) * 100
if percentage_score >= 60:
save_result(st.session_state['full_name'], percentage_score)
st.session_state['test_completed'] = True
希望这有所帮助!
有关Streamlit中的会话状态的更多信息,可以在以下资源中找到:
- https://docs.streamlit.io/library/advanced-features/session-state
- https://docs.streamlit.io/library/api-reference/session-state
英文:
It seems like session state was missing in your original code and so it's added.
The app now allow users to add their name and info, click on submit, then perform the 3 question quiz and submit. Afterwards, they can download the test results with a download button which was missing in the original code.
import streamlit as st
import pandas as pd
st.title('Employer Test')
if 'form_submitted' not in st.session_state:
st.session_state['form_submitted'] = False
if 'test_completed' not in st.session_state:
st.session_state['test_completed'] = False
def save_result(full_name, score):
data = {'Full Name': [full_name], 'Score': [score]}
df = pd.DataFrame(data)
df.to_csv('test_results.csv', index=False)
csv = df.to_csv().encode('utf-8')
st.success('Result saved successfully!')
st.download_button(
label="Download test results",
data=csv,
file_name='test_results.csv',
mime='text/csv',
)
if not st.session_state['form_submitted']:
st.markdown('## Candidate Information')
with st.form(key='candidate_info'):
# Full Name Input
full_name = st.text_input('Full Name')
# Experience Dropdown
experience = st.selectbox("Experience", ["Fresher"], index=0)
# Language Dropdown
language = st.selectbox("Language", ["Python"], index=0)
# Button to start the test
submit_button = st.form_submit_button('Submit')
if submit_button:
st.session_state['form_submitted'] = True
st.session_state['full_name'] = full_name
if st.session_state['form_submitted'] and not st.session_state['test_completed']:
st.title('Python Test')
# Dummy test questions and answers
questions = [
{
'question': 'What is the output of the following code?\n\n```python\nx = 5\nprint(x)\n```',
'options': ['5', '10', '0', 'Error'],
'correct_answer': '5'
},
{
'question': 'Which of the following is a Python data type?',
'options': ['List', 'Streamlit', 'GitHub', 'HTML'],
'correct_answer': 'List'
},
{
'question': 'What is the result of the expression 3 + 7 * 2?',
'options': ['13', '20', '17', 'Error'],
'correct_answer': '17'
}
# Add more questions here...
]
total_questions = len(questions)
score = 0
answer = []
for i, question_data in enumerate(questions):
question = question_data['question']
options = question_data['options']
correct_answer = question_data['correct_answer']
st.write(f'Question {i+1}: {question}')
# Display options for each question
answer.append(st.text_area(f"Enter answer for Question {i+1}", key=f"answer_{i}"))
# Add a submit button
if st.button("Submit Test", key="submit_test"):
# Process the answers and calculate score
for i, ans in enumerate(answer):
if ans == questions[i]['correct_answer']:
score += 1
st.write(f"Question {i+1} Answer: {ans}")
percentage_score = (score / total_questions) * 100
if percentage_score >= 60:
save_result(st.session_state['full_name'], percentage_score)
st.session_state['test_completed'] = True
Hope this helps!
More info on Session state in Streamlit can be found in the following resources:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论