用python、tkinter、mysql做一个学生答题系统
时间: 2023-11-09 14:08:46 浏览: 147
基于tkinter的答题系统
好的,下面是一个简单的学生答题系统的代码示例,使用Python、Tkinter和MySQL:
1. 创建MySQL数据库
首先需要创建一个MySQL数据库,可以使用以下命令:
```
CREATE DATABASE student_question;
```
然后创建一个名为“questions”的表,包含以下字段:
- id(主键,自增长)
- question(题目)
- answer(答案)
可以使用以下命令创建表:
```
CREATE TABLE questions (
id INT AUTO_INCREMENT PRIMARY KEY,
question VARCHAR(255) NOT NULL,
answer VARCHAR(255) NOT NULL
);
```
2. 编写Python代码
导入所需的模块:
```python
import tkinter as tk
import mysql.connector
```
连接MySQL数据库:
```python
db = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="student_question"
)
```
创建Tkinter窗口和标签:
```python
window = tk.Tk()
window.title("学生答题系统")
question_label = tk.Label(window, text="题目")
question_label.pack()
answer_label = tk.Label(window, text="答案")
answer_label.pack()
```
从MySQL数据库中获取题目:
```python
cursor = db.cursor()
cursor.execute("SELECT * FROM questions")
questions = cursor.fetchall()
current_question = 0
```
创建回答问题的函数:
```python
def answer_question():
global current_question
user_answer = answer_entry.get()
if user_answer == questions[current_question][2]:
result_label.config(text="回答正确!")
else:
result_label.config(text="回答错误!")
current_question += 1
if current_question >= len(questions):
current_question = 0
question_label.config(text=questions[current_question][1])
answer_entry.delete(0, tk.END)
```
创建Tkinter小部件,包括问题标签、答案输入框、提交按钮和结果标签:
```python
question_label.config(text=questions[current_question][1])
answer_entry = tk.Entry(window)
answer_entry.pack()
submit_button = tk.Button(window, text="提交", command=answer_question)
submit_button.pack()
result_label = tk.Label(window, text="")
result_label.pack()
```
运行Tkinter应用程序:
```python
window.mainloop()
```
完整代码示例:
```python
import tkinter as tk
import mysql.connector
db = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="student_question"
)
window = tk.Tk()
window.title("学生答题系统")
question_label = tk.Label(window, text="题目")
question_label.pack()
answer_label = tk.Label(window, text="答案")
answer_label.pack()
cursor = db.cursor()
cursor.execute("SELECT * FROM questions")
questions = cursor.fetchall()
current_question = 0
def answer_question():
global current_question
user_answer = answer_entry.get()
if user_answer == questions[current_question][2]:
result_label.config(text="回答正确!")
else:
result_label.config(text="回答错误!")
current_question += 1
if current_question >= len(questions):
current_question = 0
question_label.config(text=questions[current_question][1])
answer_entry.delete(0, tk.END)
question_label.config(text=questions[current_question][1])
answer_entry = tk.Entry(window)
answer_entry.pack()
submit_button = tk.Button(window, text="提交", command=answer_question)
submit_button.pack()
result_label = tk.Label(window, text="")
result_label.pack()
window.mainloop()
```
阅读全文