我不断收到错误: “DuplicateWidgetID:有多个小部件具有相同的 key='submit_answer'。”
我正在尝试遍历这些问题,但看起来它仍然同时拉动所有会话状态。然后抛出重复的小部件错误。
所以我很好奇应该对会话状态代码进行哪些更改,以便更好地迭代?或者开放寻求任何其他建议。我正在尝试创建一个是/否问题的游戏。你可以一次回答一个问题,它会告诉你你是对还是错。最后也给出总分。
import streamlit as st
import pandas as pd
def main():
st.title('Employer Test') # Check if 'started' key exists in session_state, if not, display candidate information
if not st.session_state.get('started'):
st.markdown('## Candidate Information')
# Full Name Input
full_name = st.text_input('Full Name')
# Experience Dropdown
experience = st.selectbox("Experience", [" Showcase"], index=0)
# Language Dropdown
language = st.selectbox("Type of Game", [" Game"], index=0)
# Button to start the test
if st.button('Submit'):
if full_name:
st.session_state['started'] = True
st.session_state['full_name'] = full_name
run_python_test()
else:
run_python_test()
def run_python_test():
st.title('Is the follow statement or question related to XYZ')
# Dummy test questions and answers
questions = [
{ 'question': 'Question 1',
'options': ['Yes', 'No'],
'correct_answer': 'Yes'
},
{
'question': 'Question 2',
'options': ['Yes', 'No'],
'correct_answer': 'No'
},
{
'question': 'Question 3',
'options': ['Yes', 'No'],
'correct_answer': 'Yes'
}
# Add more questions here...
]
total_questions = len(questions)
if 'answer' not in st.session_state:
st.session_state['answer'] = [''] * total_questions
for i, question_data in enumerate(questions):
question = question_data['question']
st.write(f'Question {i+1}: {question}')
# Display options for each question
st.session_state['answer'][i] = st.text_area(f"Enter answer for Question {i+1}", value=st.session_state['answer'][i], key=f"answer_{i}")
# Add a submit button
if st.button("Submit Test", key="submit_answer"):
score = 0
# Process the answers and calculate score
for i, ans in enumerate(st.session_state['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
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')
if __name__ == '__main__':
main()
Streamlit
st.session_state
的行为类似于字典,因此您只能将唯一标识符作为键。此外,使用显式键创建的每个小部件都会添加到状态中。
也就是说,您的问题是您正在为每个问题创建一个具有相同键的提交按钮。如果你想这样做,你需要为按钮提供唯一的标识符,就像:
for i, question_data in enumerate(questions):
# ...
if st.button("Submit Test", key=f"submit_answer_{i}"):
# ...
否则,您可以重新配置您的应用程序以使用 st.form 和 st.form_submit_button。