T 流年印迹
流年印迹
首页 Python 正文

Python 100 天 · 第 34 天:用类写 GUI:API 题库问答

这是「Python 100 天」系列第 34 天的学习笔记:用类写 GUI:API 题库问答。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

从开放题库 API 拉 10 道判断题,用 Tkinter 做成图形界面:显示题目、点 True/False、答对变绿答错变红、1 秒后下一题、右上角实时分数。README 知识点:反转义 HTML 实体、用类组织 Tkinter 界面、类型提示(Type Hints)。

一、HTML 实体反转义

API 返回的题目里常带转义字符:

1
"Hello" & goodbye

直接显示就是一堆 "。html.unescape() 把它还原:

1
2
import html
html.unescape(""Hi" & bye") # '"Hi" & bye'

这类"数据在传输中被转义"的情况非常普遍(HTML、URL、JSON 字符串都会),看到 &xxx; 或 %xx 就该想到 unescape。

二、类型提示

1
2
def __init__(self, quiz_brain: QuizBrain):
def next_question(self) -> str:

参数: 类型 和 -> 返回类型 就是类型提示。Python 不会在运行时检查它,它只是给人和编辑器看的(IDE 能做补全和静态检查,mypy 能做检查)。好处是接口意图清晰,尤其在有多个类协作时。

三、用类封装界面

1
2
3
4
5
6
class QuizInterface:
def __init__(self, quiz_brain: QuizBrain):
self.quiz = quiz_brain
self.window = Tk()
...
self.window.mainloop()

把窗口、控件、状态都收进 self,好处是回调函数能访问同一份状态(self.quiz、self.canvas),不用满屏 global。这比 Day 27–31 的"函数 + 全局变量"结构更工程化。

代码全文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from question_model import Question
from data import question_data
from quiz_brain import QuizBrain
from ui import QuizInterface

question_bank = []
for question in question_data:
question_text = question["question"]
question_answer = question["correct_answer"]
new_question = Question(question_text, question_answer)
question_bank.append(new_question)

quiz = QuizBrain(question_bank)
quiz_ui = QuizInterface(quiz)

print("You've completed the quiz")
print(f"Your final score was: {quiz.score}/{quiz.question_number}")

data.py(从 API 取题)

1
2
3
4
5
6
7
8
9
10
11
12
import requests


parameters = {
"amount": 10,
"type": "boolean",
"category": 18,
}
response = requests.get(url="https://opentdb.com/api.php", params=parameters)
response.raise_for_status()
data = response.json()
question_data = data["results"]

quiz_brain.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import html


class QuizBrain:

def __init__(self, q_list):
self.question_number = 0
self.score = 0
self.question_list = q_list
self.current_question = None

def still_has_questions(self):
return self.question_number < len(self.question_list)

def next_question(self):
self.current_question = self.question_list[self.question_number]
self.question_number += 1
q_text = html.unescape(self.current_question.text)
return f"Q.{self.question_number}: {q_text}"

def check_answer(self, user_answer):
correct_answer = self.current_question.answer
if user_answer.lower() == correct_answer.lower():
self.score += 1
return True
else:
return False

ui.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from tkinter import *
from quiz_brain import QuizBrain


THEME_COLOR = "#375362"


class QuizInterface:

def __init__(self, quiz_brain: QuizBrain):
self.quiz = quiz_brain
self.window = Tk()
self.window.title("Quiz Game")
self.window.config(padx=20, pady=20, bg=THEME_COLOR)

self.canvas = Canvas(height=250, width=300, bg="white")
self.canvas.grid(column=0, row=1, columnspan=2, pady=50)
self.question_text = self.canvas.create_text(
150,
125,
width=280,
text=f"test",
fill=THEME_COLOR,
font=("Arial", 20, "italic")
)

self.score_text = Label(
text="Score: 0",
fg="white",
bg=THEME_COLOR,
font=("Arial", 20, "italic")
)
self.score_text.grid(column=1, row=0)

true_png = PhotoImage(file="images/true.png")
self.true_button = Button(image=true_png, highlightthickness=0, command=self.answer_true)
self.true_button.grid(column=0, row=2)

false_png = PhotoImage(file="images/false.png")
self.false_button = Button(image=false_png, highlightthickness=0, command=self.answer_false)
self.false_button.grid(column=1, row=2)

self.get_next_question()

self.window.mainloop()

def get_next_question(self):
self.canvas.config(bg="white")
if self.quiz.still_has_questions():
self.score_text.config(text=f"Score: {self.quiz.score}")
q_text = self.quiz.next_question()
self.canvas.itemconfig(self.question_text, text=q_text)
else:
self.canvas.itemconfig(self.question_text, text="You've reached the end of the quiz.")
self.true_button.config(state="disabled")
self.false_button.config(state="disabled")

def answer_false(self):
is_right = self.quiz.check_answer("False")
self.give_feedback(is_right)

def answer_true(self):
is_right = self.quiz.check_answer("True")
self.give_feedback(is_right)

def give_feedback(self, is_right):
if is_right:
self.canvas.config(bg="green")
else:
self.canvas.config(bg="red")
self.window.after(1000, self.get_next_question)

代码走读

  1. data.py:带 amount=10、type=boolean、category=18(计算机)三个参数请求题库,question_data = data["results"]。
  2. main.py:把 API 的字典列表转成 Question 对象列表(和 Day 17 完全一样的套路),再交给 QuizBrain 和 QuizInterface。
  3. QuizBrain.next_question():取当前题 → 题号 +1 → html.unescape → 返回格式化后的字符串(注意这里用 return 而不是 print,界面层负责显示)。
  4. check_answer(user_answer):不接收正确答案参数,直接用 self.current_question.answer——因为"当前题"已经存在对象里,状态内聚。
  5. QuizInterface.__init__:建窗口、画布、分数标签、两个图片按钮,最后 get_next_question() + mainloop()。
  6. give_feedback(is_right):画布变绿/变红,window.after(1000, self.get_next_question) 1 秒后换题——用颜色给即时反馈,这是游戏化设计的核心。
  7. 题目全部答完后,禁用按钮并显示结束语。

一个必须知道的坑:PhotoImage 被回收

1
2
true_png = PhotoImage(file="images/true.png")     # 局部变量
self.true_button = Button(image=true_png, ...)

__init__ 执行完后,true_png 这个局部变量就没了,如果没有别的引用,图片对象会被垃圾回收,按钮变成空白。正确写法是挂到 self 上:

1
self.true_png = PhotoImage(file="images/true.png")

Tkinter 只保存了图片的名字,不负责持有对象——这是 Tkinter 最著名的坑之一。

运行效果

深紫色背景,白色卡片显示题目,底部两个圆形按钮;答对卡片闪绿、答错闪红,右上角分数实时更新。

易错点

  1. mainloop() 之后的代码不会执行:main.py 里最后的 print("完成") 其实在窗口关闭后才打印。
  2. after 里传 self.get_next_question 不带括号:带了就立刻执行。
  3. width=280 的 create_text:这个参数让文字自动换行,少了它长题目会超出画布。
  4. API 偶发返回 0 道题(response_code != 0):question_bank 为空,next_question 立刻 IndexError。

动手改

  • 加"重新开始"按钮:重建 QuizBrain 并清空分数。
  • 把类别 category=18 做成下拉框,支持换题库。
  • 用 try/except requests.RequestException 包住取题,失败时用本地备用题库。

源文件逐个讲解

6 个文件 + 2 张图,这是 Day 17 的「GUI 重制版」:

文件 行数 职责
data.py13从 API 抓题(不再用本地列表)
question_model.py6Question 类(没变)
quiz_brain.py29出题 + 判分,next_question 改成返回字符串
ui.py72QuizInterface 类:整个界面
main.py18组装(比 Day 17 还短)
README.md8说明页
images/true.png / false.png2.5KB / 2.8KB✔ / ✘ 按钮

data.py(13 行)——模块级就发请求

1
2
3
4
5
6
7
8
9
10
11
import requests

parameters = {
"amount": 10,
"type": "boolean",
"category": 18,
}
response = requests.get(url="https://opentdb.com/api.php", params=parameters)
response.raise_for_status()
data = response.json()
question_data = data["results"]

import data 的那一刻就发了一次 HTTP 请求——这行代码在模块级,不是函数里。后果:没网就 import 失败,整个程序起不来。

三个参数的含义:

  • amount: 10:要 10 道题;
  • type: "boolean":只要判断题(对/错),因为界面只有两个按钮;
  • category: 18:计算机科学类。

question_data = data["results"]:OpenTDB 返回的是 {"response_code": 0, "results": [...]},题目在 results 里。

每条题目长这样:

1
2
3
4
5
6
7
8
{
"category": "Science: Computers",
"type": "boolean",
"difficulty": "medium",
"question": "What is the &quot;S&quot; in &quot;HTTPS&quot;?",
"correct_answer": "Secure",
"incorrect_answers": ["..."]
}

注意 &quot;——HTML 实体,下一节要处理。

quiz_brain.py(29 行)——两处关键改动

1
import html

新增 html 模块,只为一行:

1
2
        q_text = html.unescape(self.current_question.text)
return f"Q.{self.question_number}: {q_text}"

html.unescape() 把 &quot; 还原成 "。不转的话,题目里会显示 What is the &quot;S&quot;...,很难看。

next_question 从「打印」改成「返回字符串」:

Day 17 Day 34
input(...) 在这里问返回字符串,由 UI 显示
check_answer 打印结果返回 True/False

这就是「业务逻辑和界面分离」:QuizBrain 不知道有窗口,UI 不知道题目怎么来的。

1
2
3
4
5
6
7
    def check_answer(self, user_answer):
correct_answer = self.current_question.answer
if user_answer.lower() == correct_answer.lower():
self.score += 1
return True
else:
return False

self.current_question 是新增的实例属性,在 next_question 里赋值——这样 check_answer 不用再传题目进来。

参数从 (user_answer, correct_answer) 变成 (user_answer),因为正确答案存在对象里了。

ui.py(72 行)——全书的「GUI 类」范本

1
2
3
4
class QuizInterface:
def __init__(self, quiz_brain: QuizBrain):
self.quiz = quiz_brain
self.window = Tk()

quiz_brain: QuizBrain 是类型标注(type hint)——Python 不强制检查,只是给人和 IDE 看的。它的价值在这里:写 self.quiz. 时 IDE 会提示 next_question、check_answer,不用回去翻文件。

「依赖注入」:QuizInterface 不自己 new 一个 QuizBrain,而是从外面传进来。好处是测试时可以传一个假的 QuizBrain。

1
2
3
4
5
6
7
8
9
        self.canvas = Canvas(height=250, width=300, bg="white")
self.canvas.grid(column=0, row=1, columnspan=2, pady=50)
self.question_text = self.canvas.create_text(
150, 125,
width=280,
text=f"test",
fill=THEME_COLOR,
font=("Arial", 20, "italic")
)

width=280 是「文字自动换行宽度」——Canvas 文字超过 280 像素就折行。不设的话长题目会超出卡片。

text=f"test" 里的 f 是多余的(没有占位符),只是作者习惯。

1
2
        true_png = PhotoImage(file="images/true.png")
self.true_button = Button(image=true_png, highlightthickness=0, command=self.answer_true)

true_png 是局部变量! 这是潜在的内存回收问题——PhotoImage 只被 Button 内部引用,Tkinter 的 Button 会持有它,所以这份代码能跑。但换成 Canvas.create_image 时就必须存成 self.xxx(Day 28 讲过的坑)。

command=self.answer_true:绑定的是实例方法,Tkinter 调用时不会传参(self 由绑定自动带上)。

1
2
        self.get_next_question()
self.window.mainloop()

mainloop() 写在 __init__ 里——这是这份代码最值得批评的设计:构造函数「不返回」了,永远卡在事件循环里。于是 main.py 里 QuizInterface(quiz) 之后的 print 要等窗口关闭才执行。更好的是让 main() 调 mainloop()。

1
2
3
4
5
6
7
8
9
10
    def get_next_question(self):
self.canvas.config(bg="white")
if self.quiz.still_has_questions():
self.score_text.config(text=f"Score: {self.quiz.score}")
q_text = self.quiz.next_question()
self.canvas.itemconfig(self.question_text, text=q_text)
else:
self.canvas.itemconfig(self.question_text, text="You've reached the end of the quiz.")
self.true_button.config(state="disabled")
self.false_button.config(state="disabled")

每换一题先把背景刷白(上一题的绿/红要清掉)。结束时禁用两个按钮(state="disabled"),防止继续点。

1
2
3
4
5
6
7
8
9
10
    def answer_true(self):
is_right = self.quiz.check_answer("True")
self.give_feedback(is_right)

def give_feedback(self, is_right):
if is_right:
self.canvas.config(bg="green")
else:
self.canvas.config(bg="red")
self.window.after(1000, self.get_next_question)

after(1000, ...) 让绿/红背景停留 1 秒再换题——不 sleep,界面不冻(Day 28 讲过)。

main.py(18 行)

1
2
3
4
5
quiz = QuizBrain(question_bank)
quiz_ui = QuizInterface(quiz)

print("You've completed the quiz")
print(f"Your final score was: {quiz.score}/{quiz.question_number}")

这两行 print 要等窗口关掉才出现——因为 QuizInterface.__init__ 里卡在 mainloop()。这就是「把 mainloop 塞进构造函数」的直接后果。

这份代码的问题

  1. mainloop() 在 __init__ 里,构造对象等于「阻塞到窗口关闭」。
  2. data.py 在模块级发请求,没网就 import 失败。
  3. true_png 是局部变量(这里侥幸没事,但不是好习惯)。
  4. 题目只有 10 道、答完不能重开。
  5. type: "boolean" 保证了只有对/错,但如果 API 返回别的类型,check_answer 永远判错。

README.md(8 行)

标题 Day 34 - API Practice - Creating a GUI Quiz App,知识点:Understand API、HTTP Requests、Handle HTML Entities、API Parameters、Quiz App。

Handle HTML Entities 就是那一行 html.unescape()——这是很多人做 API 项目时忽略的细节。

六个文件的关系

1
2
3
4
5
data.py(HTTP)──▶ question_data
↓
main.py ──构造 Question 对象──▶ QuizBrain ──▶ QuizInterface(ui)
↓
按钮 → check_answer → 改背景色

和 Day 17 对比:question_model.py 几乎没变,quiz_brain.py 改了 2 个方法的签名,data.py 从静态列表变成网络请求,新增的只有 ui.py。这就是「界面可替换、业务不动」的实例。

微信收款码 微信
支付宝收款码 支付宝
评论