用python、tkinter、mysql做学生答题系统
时间: 2023-12-22 20:02:29 浏览: 147
好的,下面是一个简单的学生答题系统的程序,使用Python、Tkinter和MySQL数据库:
首先,需要安装mysql-connector-python库,用于连接MySQL数据库,可以使用以下命令进行安装:
```
pip install mysql-connector-python
```
然后,建立一个名为“students”的数据库,包含两个表格:题目表格(questions)和学生答题表格(answers)。
题目表格(questions)包含以下字段:
- id: 题目编号
- question: 题目内容
- answer: 正确答案
学生答题表格(answers)包含以下字段:
- id: 学生编号
- question_id: 题目编号
- answer: 学生答案
接下来,可以创建一个Python文件,命名为“student_quiz_system.py”,代码如下:
```python
import mysql.connector
import tkinter as tk
from tkinter import messagebox
# 连接MySQL数据库
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="students"
)
# 创建主窗口
root = tk.Tk()
root.title("学生答题系统")
# 创建题目标签和答案输入框
question_label = tk.Label(root, text="题目")
question_label.pack()
answer_entry = tk.Entry(root)
answer_entry.pack()
# 查询题目
def get_question():
# 从题目表格中随机获取一条题目
cursor = mydb.cursor()
cursor.execute("SELECT id, question, answer FROM questions ORDER BY RAND() LIMIT 1")
question = cursor.fetchone()
# 显示题目
question_label.config(text=question[1])
# 将题目编号和正确答案保存到全局变量中
global question_id, correct_answer
question_id = question[0]
correct_answer = question[2]
# 提交答案
def submit_answer():
# 获取学生答案
student_answer = answer_entry.get()
# 将学生答案保存到答题表格中
cursor = mydb.cursor()
cursor.execute("INSERT INTO answers (id, question_id, answer) VALUES (NULL, %s, %s)", (question_id, student_answer))
mydb.commit()
# 判断答案是否正确
if student_answer == correct_answer:
messagebox.showinfo("提示", "回答正确")
else:
messagebox.showerror("错误", "回答错误")
# 获取下一题
get_question()
# 创建按钮
submit_button = tk.Button(root, text="提交", command=submit_answer)
submit_button.pack()
# 获取第一题
get_question()
# 运行主循环
root.mainloop()
```
运行程序后,会显示一个窗口,随机获取一道题目,并显示在窗口中。学生可以在答案输入框中输入答案,然后点击“提交”按钮进行答题。程序会将学生的答案保存到答题表格中,并判断答案是否正确,然后随机获取下一道题目,重复以上步骤。
阅读全文
相关推荐














