用py制作一个具有上下题功能的答题系统
时间: 2024-03-15 10:45:16 浏览: 17
可以使用Python的tkinter库来制作具有上下题功能的答题系统。下面是一个简单的示例代码,你可以根据自己的需求进行修改和完善:
```python
from tkinter import *
from tkinter import messagebox
# 定义题目和答案
questions = [
{"question": "1+1=?", "options": ["1", "2", "3", "4"], "answer": "2"},
{"question": "2+2=?", "options": ["2", "3", "4", "5"], "answer": "4"},
{"question": "3+3=?", "options": ["4", "5", "6", "7"], "answer": "6"},
{"question": "4+4=?", "options": ["6", "7", "8", "9"], "answer": "8"},
{"question": "5+5=?", "options": ["8", "9", "10", "11"], "answer": "10"}
]
# 定义变量
current_question = 0
score = 0
# 定义函数
def show_question():
global current_question
question = questions[current_question]
question_label.config(text=question["question"])
option1.config(text=question["options"][0])
option2.config(text=question["options"][1])
option3.config(text=question["options"][2])
option4.config(text=question["options"][3])
def check_answer(answer):
global current_question
global score
question = questions[current_question]
if question["answer"] == answer:
score += 1
current_question += 1
if current_question == len(questions):
messagebox.showinfo("答题完成", f"您的得分为{score}分")
root.destroy()
else:
show_question()
def previous_question():
global current_question
if current_question > 0:
current_question -= 1
show_question()
def next_question():
global current_question
if current_question < len(questions) - 1:
current_question += 1
show_question()
# 创建窗口和控件
root = Tk()
root.title("答题系统")
question_label = Label(root, text="")
question_label.pack()
option1 = Button(root, text="", command=lambda: check_answer(questions[current_question]["options"][0]))
option1.pack()
option2 = Button(root, text="", command=lambda: check_answer(questions[current_question]["options"][1]))
option2.pack()
option3 = Button(root, text="", command=lambda: check_answer(questions[current_question]["options"][2]))
option3.pack()
option4 = Button(root, text="", command=lambda: check_answer(questions[current_question]["options"][3]))
option4.pack()
previous_button = Button(root, text="上一题", command=previous_question)
previous_button.pack(side=LEFT)
next_button = Button(root, text="下一题", command=next_question)
next_button.pack(side=RIGHT)
show_question()
root.mainloop()
```
在这个示例代码中,我们首先定义了题目和答案,然后创建了窗口和控件。在控件中,我们使用了`Label`控件显示题目,使用`Button`控件作为选项,并且为每个选项绑定了一个回调函数,在点击选项时会检查答案是否正确,并且切换到下一题。同时,我们还创建了“上一题”和“下一题”两个按钮,通过点击这两个按钮可以切换当前显示的题目。在检查答案时,如果当前已经是最后一题,则会弹出一个消息框显示最终得分,并且退出程序。
你可以在这个示例代码的基础上进行修改和扩展,添加更多的题目和选项,或者改变题目和选项的显示方式。