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

Python 100 天 · 第 83 天:井字棋:Tkinter 网格与弹窗

这是「Python 100 天」系列第 83 天的学习笔记:井字棋:Tkinter 网格与弹窗。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

用 Tkinter 做一个双人井字棋:3×3 按钮网格,点击落子,X/O 自动轮换,连成三子就弹窗宣布获胜并禁用所有按钮。README 知识点:Tkinter 窗口与 Label、grid() 与 columnspan 布局、对话框与弹窗。

一、Tkinter 的三个基本件

1
2
3
4
5
6
7
8
from tkinter import *
from tkinter import messagebox

root = Tk() # 主窗口
root.title('Tic Tac Toe')

button = Button(root, text="", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace", command=lambda: b_click(button))
button.grid(row=0, column=0)
  • Tk() 是整个应用的根窗口,一个程序只有一个;
  • grid(row=, column=) 是网格布局(还有 pack() 顺序排列、place() 绝对坐标);
  • command= 绑点击事件,注意写 lambda,否则函数会在创建时立刻执行。

二、9 个按钮的三种写法

这份代码选择了最直白的:

1
2
3
4
b1 = Button(root, ...); b1.grid(row=0, column=0)
b2 = Button(root, ...); b2.grid(row=0, column=1)
...
b9 = Button(root, ...); b9.grid(row=2, column=2)

可以改成列表,代码立刻短一半:

1
2
3
4
5
6
buttons = []
for i in range(9):
b = Button(root, text="", font=("Helvetica", 20), height=3, width=6)
b.grid(row=i//3, column=i%3)
b.config(command=lambda b=b: b_click(b))
buttons.append(b)

i//3 是行、i%3 是列——"一维下标 → 二维坐标"的标准换算。lambda b=b: 是"绑定当前循环变量"的经典技巧(不写会全部指向最后一个按钮)。

三、胜负判断的暴力法

1
2
3
if b1['text'] == "X" and b2['text'] == 'X' and b3['text'] == 'X':
...
elif b4['text'] == "X" and ...

8 条获胜线 × 2 个玩家 = 16 个 elif 分支,每个分支重复三行 config(bg="green") + 弹窗 + 禁用。

能跑,但是反面教材。数据驱动写法:

1
2
3
4
5
6
7
8
9
WINS = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]

for a, b, c in WINS:
if buttons[a]['text'] == buttons[b]['text'] == buttons[c]['text'] != "":
for i in (a, b, c):
buttons[i].config(bg="green")
winner = buttons[a]['text']
messagebox.showinfo("Tic Tac Toe", f"{winner} is the winner!")
break

8 行替代 100 行,而且加"四子棋"只要改 WINS。这是"数据与逻辑分离"的最好例子。

四、全局变量

1
2
3
4
5
6
clicked = True
count = 0

def if_winner():
global winner
winner = False

global 让函数内部能改模块级变量。这是 Tkinter 小项目的常见做法,但很脆:状态散落在全局,函数互相依赖。更好的做法是包一个 class TicTacToe:,把 clicked/count/winner 变成 self.xxx。

五、弹窗

1
2
from tkinter import messagebox
messagebox.showinfo("Tic Tac Toe", "X is the winner!")

四种:showinfo(信息)、showwarning、showerror、askyesno(返回 True/False)。弹窗会阻塞程序,直到用户点确定。

代码全文

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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# 导入 tkinter 的全部名字(Button/Tk/Menu/DISABLED 等)。
# 小项目图省事常这么写;正式项目建议 import tkinter as tk,避免命名空间被污染。
from tkinter import *
# messagebox 是子模块,不会被 `import *` 带进来,必须单独导入。
from tkinter import messagebox


# 创建主窗口(Tk 实例)。一个程序只能有一个根窗口。
root = Tk()
# 窗口标题栏文字。
root.title('Tic Tac Toe')

# 轮到谁:True = X 落子,False = O 落子。用模块级变量是因为多个函数都要改它。
clicked = True
# 已落子数,用来判断“棋盘满了还没人赢 = 平局”。
count = 0


# 结束局面时把 9 个按钮全部禁用,防止继续点击。
def disable_all_buttons():
# config(state=DISABLED):修改控件属性;DISABLED 是 tkinter 常量,表示不可点击。
b1.config(state=DISABLED)
b2.config(state=DISABLED)
b3.config(state=DISABLED)
b4.config(state=DISABLED)
b5.config(state=DISABLED)
b6.config(state=DISABLED)
b7.config(state=DISABLED)
b8.config(state=DISABLED)
b9.config(state=DISABLED)


# 胜负判定:3 行 + 3 列 + 2 条对角线,共 8 条线;X、O 各一遍,所以是 16 个分支。
def if_winner():
# global 声明:下面给 winner 赋值,改的是模块级变量而不是新建局部变量。
global winner
# 先假设没人赢,命中某条线再置 True。
winner = False

# b1['text'] 是“读取控件选项”的简写,等价于 b1.cget('text')。
if b1['text'] == "X" and b2['text'] == 'X' and b3['text'] == 'X':
# 把获胜的三个格子染成绿色作为视觉提示。
b1.config(bg="green")
b2.config(bg="green")
b3.config(bg="green")
winner = True
# messagebox.showinfo(标题, 内容):模态提示框,会阻塞直到用户点确定。
messagebox.showinfo("Tic Tac Toe", "X is the winner!")
disable_all_buttons()

elif b4['text'] == "X" and b5['text'] == 'X' and b6['text'] == 'X':
b4.config(bg="green")
b5.config(bg="green")
b6.config(bg="green")
winner = True
messagebox.showinfo("Tic Tac Toe", "X is the winner!")
disable_all_buttons()

elif b7['text'] == "X" and b8['text'] == 'X' and b9['text'] == 'X':
b7.config(bg="green")
b8.config(bg="green")
b9.config(bg="green")
winner = True
messagebox.showinfo("Tic Tac Toe", "X is the winner!")
disable_all_buttons()

elif b1['text'] == "X" and b4['text'] == 'X' and b7['text'] == 'X':
b1.config(bg="green")
b4.config(bg="green")
b7.config(bg="green")
winner = True
messagebox.showinfo("Tic Tac Toe", "X is the winner!")
disable_all_buttons()

elif b2['text'] == "X" and b5['text'] == 'X' and b8['text'] == 'X':
b2.config(bg="green")
b5.config(bg="green")
b8.config(bg="green")
winner = True
messagebox.showinfo("Tic Tac Toe", "X is the winner!")
disable_all_buttons()

elif b3['text'] == "X" and b6['text'] == 'X' and b9['text'] == 'X':
b3.config(bg="green")
b6.config(bg="green")
b9.config(bg="green")
winner = True
messagebox.showinfo("Tic Tac Toe", "X is the winner!")
disable_all_buttons()

elif b1['text'] == "X" and b5['text'] == 'X' and b9['text'] == 'X':
b1.config(bg="green")
b5.config(bg="green")
b9.config(bg="green")
winner = True
messagebox.showinfo("Tic Tac Toe", "X is the winner!")
disable_all_buttons()

elif b3['text'] == "X" and b5['text'] == 'X' and b7['text'] == 'X':
b3.config(bg="green")
b5.config(bg="green")
b7.config(bg="green")
winner = True
messagebox.showinfo("Tic Tac Toe", "X is the winner!")
disable_all_buttons()

elif b1['text'] == "O" and b2['text'] == 'O' and b3['text'] == 'O':
b1.config(bg="green")
b2.config(bg="green")
b3.config(bg="green")
winner = True
messagebox.showinfo("Tic Tac Toe", "O is the winner!")
disable_all_buttons()

elif b4['text'] == "O" and b5['text'] == 'O' and b6['text'] == 'O':
b4.config(bg="green")
b5.config(bg="green")
b6.config(bg="green")
winner = True
messagebox.showinfo("Tic Tac Toe", "O is the winner!")
disable_all_buttons()

elif b7['text'] == "O" and b8['text'] == 'O' and b9['text'] == 'O':
b7.config(bg="green")
b8.config(bg="green")
b9.config(bg="green")
winner = True
messagebox.showinfo("Tic Tac Toe", "O is the winner!")
disable_all_buttons()

elif b1['text'] == "O" and b4['text'] == 'O' and b7['text'] == 'O':
b1.config(bg="green")
b4.config(bg="green")
b7.config(bg="green")
winner = True
messagebox.showinfo("Tic Tac Toe", "O is the winner!")
disable_all_buttons()

elif b2['text'] == "O" and b5['text'] == 'O' and b8['text'] == 'O':
b2.config(bg="green")
b5.config(bg="green")
b8.config(bg="green")
winner = True
messagebox.showinfo("Tic Tac Toe", "O is the winner!")
disable_all_buttons()

elif b3['text'] == "O" and b6['text'] == 'O' and b9['text'] == 'O':
b3.config(bg="green")
b6.config(bg="green")
b9.config(bg="green")
winner = True
messagebox.showinfo("Tic Tac Toe", "O is the winner!")
disable_all_buttons()

elif b1['text'] == "O" and b5['text'] == 'O' and b9['text'] == 'O':
b1.config(bg="green")
b5.config(bg="green")
b9.config(bg="green")
winner = True
messagebox.showinfo("Tic Tac Toe", "O is the winner!")
disable_all_buttons()

elif b3['text'] == "O" and b5['text'] == 'O' and b7['text'] == 'O':
b3.config(bg="green")
b5.config(bg="green")
b7.config(bg="green")
winner = True
messagebox.showinfo("Tic Tac Toe", "O is the winner!")
disable_all_buttons()

# 平局:下了 9 手且 winner 仍为 False(说明 16 个分支都没命中)。
# 这个判断放在函数末尾、所有 elif 之后,所以只在“没人赢”时才可能成立。
if count == 9 and winner == False:
messagebox.showinfo("Tic Tac Toe", "It's a tie!")
disable_all_buttons()


# 点击回调:参数 b 是被点的那个按钮对象(由下面的 lambda 传进来)。
def b_click(b):
# global:要修改 clicked 与 count 这两个模块级变量。
global clicked, count

# 只有格子为空(text 是空格)才允许落子,否则弹错误框。
if b['text'] == ' ' and clicked == True:
# 直接给 text 选项赋值也能生效(tkinter 的选项既可 get 也可 set)。
b['text'] = 'X'
clicked = False
# 落子数 +1。
count += 1
# 每次落子后立刻判胜负。
if_winner()
# 轮到 O;分支结构与上面对称。
elif b['text'] == ' ' and clicked == False:
b['text'] = 'O'
clicked = True
count += 1
if_winner()
else:
# 点到已有棋子的格子:报错提示。
messagebox.showerror("Tic Tac Toe", "Please select a blank box")


# 重开一局:清空状态并重建 9 个按钮(比逐个重置 text/bg/state 简单)。
def play_again():
# 这 9 个按钮名要在函数里重新赋值,所以必须声明 global,否则会变成局部变量、
# 其它函数就读不到新按钮了(这是 tkinter 小项目最常见的坑)。
global b1, b2, b3, b4, b5, b6, b7, b8, b9
global clicked, count
clicked = True
count = 0
# Buttons
# Button(父容器, 选项...):text 初始为一个空格(代表空位),
# font 用 (字体名, 字号),height/width 以字符为单位,bg 用系统按钮色保持原生外观。
# command=lambda: b_click(b1):lambda 把“当前按钮”绑定进回调;
# 若直接写 command=b_click(b1),会在创建时就调用函数(那时按钮还没建好)。
b1 = Button(root, text=" ", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace",
command=lambda: b_click(b1))
b2 = Button(root, text=" ", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace",
command=lambda: b_click(b2))
b3 = Button(root, text=" ", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace",
command=lambda: b_click(b3))

b4 = Button(root, text=" ", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace",
command=lambda: b_click(b4))
b5 = Button(root, text=" ", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace",
command=lambda: b_click(b5))
b6 = Button(root, text=" ", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace",
command=lambda: b_click(b6))

b7 = Button(root, text=" ", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace",
command=lambda: b_click(b7))
b8 = Button(root, text=" ", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace",
command=lambda: b_click(b8))
b9 = Button(root, text=" ", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace",
command=lambda: b_click(b9))

# Button grid assign

# grid(row, column):按行列摆放,形成 3×3 棋盘。
b1.grid(row=0, column=0)
b2.grid(row=0, column=1)
b3.grid(row=0, column=2)

b4.grid(row=1, column=0)
b5.grid(row=1, column=1)
b6.grid(row=1, column=2)

b7.grid(row=2, column=0)
b8.grid(row=2, column=1)
b9.grid(row=2, column=2)


# 菜单栏:Menu(父窗口) 创建,再用 root.config(menu=...) 挂上去。
game_menu = Menu(root)
root.config(menu=game_menu)

# 下拉菜单;tearoff=False 去掉 Tk 默认那条可撕下的虚线。
options_menu = Menu(game_menu, tearoff=False)
# add_cascade:把一个子菜单挂到菜单栏上。
game_menu.add_cascade(label="Options", menu=options_menu)
# add_command:给下拉项绑定回调(这里是重开一局)。
options_menu.add_command(label="Restart", command=play_again)

# 首次进入游戏时画一遍棋盘。
play_again()
# mainloop():进入事件循环,等待鼠标/键盘事件;这行之后代码不会继续执行,
# 窗口关闭才返回。
root.mainloop()

代码走读

  1. 创建 root,设标题。
  2. 全局 clicked = True(表示轮到 X)、count = 0(已落子数)。
  3. disable_all_buttons():9 行 config(state=DISABLED)——可以改成循环。
  4. if_winner():16 个 elif 覆盖 X 和 O 的所有获胜线,命中就把三个按钮变绿、弹窗、禁用。
  5. b_click(button):若按钮已有文字直接返回;否则按 clicked 写 X 或 O、翻转 clicked、count += 1、调 if_winner()。
  6. 平局判断:count == 9 且没人赢 → 弹"平局"。

这份代码的问题

(1) 16 个分支大量重复

见上。这是最该重构的地方。

(2) global winner 但 winner 没在别处用

winner = True 设了,但主流程并没有读它——判断"是否还能点"靠的是 disable_all_buttons()。变量写了不用,说明设计没想清楚。

(3) 平局判断可能被跳过

如果第 9 步刚好赢了,if_winner() 里已经禁用按钮并弹窗,之后的"平局"判断要保证不会又弹一个窗。顺序很关键。

(4) b1['text'] 这种取值方式

widget['text'] 是 Tkinter 的"配置字典"访问法,等价 widget.cget('text')。能用,但读起来像字典操作,容易误解。

(5) 没有"重新开始"

赢了一局只能关掉程序重开。应该加一个 Reset 按钮,把 9 个按钮的 text 清空、state 恢复、bg 复原、count=0、clicked=True。

运行结果

3×3 大按钮窗口 → 点一下出现 X → 再点出现 O → 三子连线时三个格子变绿 + 弹窗"X is the winner!" → 所有按钮变灰。

易错点

  1. command=b_click(button) 加了括号:创建时就执行,之后点击无效。
  2. lambda: b_click(button) 在循环里:所有按钮都指向最后一个(要用 lambda b=button:)。
  3. grid() 和 pack() 混用在同一父容器:Tkinter 会卡死或布局错乱。
  4. messagebox 没导入:from tkinter import messagebox 必须单独写。
  5. macOS 上 bg 对某些原生按钮无效:ttk 主题按钮不吃 bg,要用 tk.Button。

动手改

  • 用 WINS 列表 + 循环重写 if_winner()。
  • 用 for i in range(9) 建按钮,删掉 b1–b9。
  • 加 Reset 按钮。
  • 进阶:加一个"电脑对手"(随机选空格 / 简单规则:先堵对方)。

源文件逐个讲解

2 个文件:

文件 规模 职责
main.py228 行Tkinter 井字棋(9 个按钮 + 胜负判定 + 菜单重开)
README.md8 行说明页

228 行里,有 130 行是「8 种连法的重复判断」——这是这一天最值得批评也最值得学的地方(后面会讲怎么压缩到 10 行)。

main.py(228 行)

(1)骨架:全局状态 + 9 个按钮

1
2
3
4
5
6
7
8
from tkinter import *
from tkinter import messagebox

root = Tk()
root.title('Tic Tac Toe')

clicked = True
count = 0

三个全局变量:

变量 含义
clicked轮到谁(True = X,False = O)
count已下几步(用于判平局)
b1…b99 个按钮(在 play_again() 里创建,靠 global 暴露)

from tkinter import *:星号导入——能少写 tkinter. 前缀,但会污染命名空间(PEP 8 不推荐,教程里常见)。

(2)disable_all_buttons():九行重复

1
2
3
4
5
def disable_all_buttons():
b1.config(state=DISABLED)
b2.config(state=DISABLED)
...
b9.config(state=DISABLED)

九行,结构完全一样——「手工展开」的典型。

更短的写法:

1
2
3
def disable_all_buttons():
for b in (b1,b2,b3,b4,b5,b6,b7,b8,b9):
b.config(state=DISABLED)

或者一开始就把按钮放进列表:buttons = [b1, ..., b9],后面所有操作都能循环。

这正是 if_winner() 那 130 行的病根:没有把「按钮」当成「数据结构」来处理。

(3)if_winner():8 种 X + 8 种 O

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def if_winner():
global winner
winner = False

if b1['text'] == "X" and b2['text'] == 'X' and b3['text'] == 'X':
b1.config(bg="green")
b2.config(bg="green")
b3.config(bg="green")
winner = True
messagebox.showinfo("Tic Tac Toe", "X is the winner!")
disable_all_buttons()

elif b4['text'] == "X" and b5['text'] == 'X' and b6['text'] == 'X':
...

8 种连法(X 和 O 各一遍,共 16 个分支):

编号 连法 按钮
1第一行b1 b2 b3
2第二行b4 b5 b6
3第三行b7 b8 b9
4第一列b1 b4 b7
5第二列b2 b5 b8
6第三列b3 b6 b9
7主对角b1 b5 b9
8副对角b3 b5 b7

每个分支做四件事(顺序固定):

  1. 三个按钮变绿(bg="green")
  2. winner = True
  3. 弹窗(messagebox.showinfo)
  4. 禁用所有按钮

b1['text'] 是「下标访问控件属性」——等价于 b1.cget("text")。这种写法短,但 IDE 不提示。

(4)判平局:count == 9 and winner == False

1
2
3
    if count == 9 and winner == False:
messagebox.showinfo("Tic Tac Toe", "It's a tie!")
disable_all_buttons()

注意这是 if 不是 elif——它和上面 16 个分支是「并列」的。

逻辑正确性:

  • 第 9 步下完 → count = 9;
  • 如果没人赢 → winner 还是 False → 弹「平局」;
  • 如果有人赢 → winner = True → 不弹平局。

⚠️ 但「9 步下完刚好赢」的情况会「先弹赢家、再判断不弹平局」——正确。

(5)b_click():落子逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def b_click(b):
global clicked, count

if b['text'] == ' ' and clicked == True:
b['text'] = 'X'
clicked = False
count += 1
if_winner()
elif b['text'] == ' ' and clicked == False:
b['text'] = 'O'
clicked = True
count += 1
if_winner()
else:
messagebox.showerror("Tic Tac Toe", "Please select a blank box")

四个判断:

条件 动作
空格 + 轮到 X写 X、切换、计数、判胜负
空格 + 轮到 O写 O、切换、计数、判胜负
非空格弹错("Please select a blank box")

b['text'] == ' ':用一个空格表示「空」——不能用 ''(Button(text='') 高度会塌)。

(6)play_again():重建 9 个按钮

1
2
3
4
5
6
7
8
9
10
11
12
13
def play_again():
global b1, b2, b3, b4, b5, b6, b7, b8, b9
global clicked, count
clicked = True
count = 0

b1 = Button(root, text=" ", font=("Helvetica", 20), height=3, width=6, bg="SystemButtonFace",
command=lambda: b_click(b1))
...
b1.grid(row=0, column=0)
b2.grid(row=0, column=1)
b3.grid(row=0, column=2)
...

关键技巧:command=lambda: b_click(b1)

不能写 command=b_click(b1)——那会「立刻调用」并把返回值(None)当回调。

必须用 lambda 包一层,把「调用」推迟到点击时。

⚠️ 但 lambda: b_click(b1) 有个「晚绑定」陷阱:

b1 是在点击时才去读的「全局变量」——如果之后 b1 被重新赋值(重开一局),旧按钮的 lambda 会调用「新的 b1」。

在这个程序里恰好没问题(旧按钮已经被覆盖、点不到了),但这是经典陷阱——稳妥写法:

1
command=lambda b=b1: b_click(b)   # 默认参数「立刻绑定」

(7)真 bug:旧按钮没有被销毁

1
2
3
4
def play_again():
global b1, ...
b1 = Button(root, ...) # 新建一个 Button
b1.grid(row=0, column=0) # 放进同一个格子

play_again() 每次调用都「新建 9 个 Button」,但旧的那 9 个还在——它们仍然 grid 在同样的格子里。

Tkinter 的行为:同一格子里后 grid 的控件会盖住先 grid 的——所以「看起来」是新的。

但旧的 9 个 widget 对象还在内存里,而且仍然绑定着 b_click——点它们(如果露出来)照样能落子。

正确做法:

1
2
for b in (b1, ..., b9):
b.destroy() # 或 b.grid_forget()

「重开一局」应该是「清空棋盘」而不是「叠一层新棋盘」——这是 Tkinter 新手最常见的资源泄漏。

(8)font=("Helvetica", 20)

font 必须是「字体描述」:

  • 元组 ("Helvetica", 20) ✅(字体名 + 字号)
  • 字符串 "Helvetica 20" ✅
  • 整数 20 ❌(会被当成字体名 "20" 去查,找不到就报错/回退)

height=3, width=6:按钮的「字符数」尺寸(不是像素)——height=3 = 3 行文字高。

(9)菜单

1
2
3
4
5
6
7
8
9
game_menu = Menu(root)
root.config(menu=game_menu)

options_menu = Menu(game_menu, tearoff=False)
game_menu.add_cascade(label="Options", menu=options_menu)
options_menu.add_command(label="Restart", command=play_again)

play_again()
root.mainloop()

三层结构:

  1. Menu(root):菜单栏
  2. Menu(game_menu, tearoff=False):下拉菜单(tearoff=False 去掉「虚线撕下」功能)
  3. add_cascade:把子菜单挂到菜单栏;add_command:加一项

root.config(menu=game_menu):把菜单栏装到窗口。

最后两行:

  • play_again():首次开局(创建 9 个按钮)
  • root.mainloop():进入事件循环(没有它窗口一闪就没了)

这份代码的问题

  1. if_winner() 130 行重复——可用「8 个三元组 + 循环」压到 10 行。
  2. play_again() 不销毁旧按钮(叠罗汉,资源泄漏)。
  3. lambda: b_click(b1) 晚绑定(应 lambda b=b1: b_click(b))。
  4. disable_all_buttons() 九行重复(应循环)。
  5. 9 个全局变量 b1…b9(应放列表)。
  6. from tkinter import *(污染命名空间)。
  7. winner 声明 global 但只在函数内用(其实不需要 global)。
  8. 没有 if __name__ == "__main__"。

「8 种连法」的优雅写法(供对照):

1
2
3
4
5
6
7
8
9
WIN_LINES = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]

def check_winner(buttons, mark):
for a,b,c in WIN_LINES:
if all(buttons[i]['text'] == mark for i in (a,b,c)):
for i in (a,b,c):
buttons[i].config(bg='green')
return True
return False

10 行,替掉 130 行——这就是「数据结构 > 重复代码」的力量。

README.md(8 行)

标题 Day 83 - Tic Tac Toe,知识点:GUI、Tkinter、Event Handling。

三个:GUI、Tkinter、事件处理。

这一天是「GUI 三连」的第一天(Day 83 井字棋 → 84 水印 → 85 打字测速),三天全用 Tkinter。

核心新概念只有一个:command=lambda: fn(参数)——「把「调用」包装成「回调」」。

这一个套路能写出所有「带参数的按钮」。

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