Python tkinter井字棋重置棋盘后误报获胜问题求助
问题排查结论
你遇到的重置后误判获胜的问题,根源出在reset函数的列表清空逻辑错误:
原代码中遍历clicked列表时,给临时循环变量element赋值为空格,并没有修改原clicked列表的实际元素,上一局的获胜状态一直残留在列表中,因此新局开始后检测逻辑会直接判定符合获胜条件弹出提示。
具体修复内容
- 修正
clicked列表清空逻辑:将reset函数中原有的无效遍历赋值,替换为通过索引直接修改原列表的每个元素 - 新增平局判定逻辑:当所有格子都被填满且无人获胜时,弹出平局提示并重置游戏
- 规范消息框标题显示,新增回合数重置逻辑,避免新局先后手顺序错乱
- 适配中文提示内容,优化使用体验
修复后完整代码
from tkinter import * from tkinter import messagebox screen = Tk() screen.title("井字棋") screen.geometry("600x600+350+10") turns = 0 pixel = PhotoImage(width=1, height=1) buttons_list = [] clicked = [" " for i in range(9)] def click(c, d): global turns turns += 1 has_been_clicked = (buttons_list[c][d].cget("text") != " ") if has_been_clicked is True: return if turns % 2 == 0: buttons_list[c][d].configure(text="X", fg="red", font=("Arial", 50)) clicked[c * 3 + d] = "X" else: buttons_list[c][d].configure(text="O", fg="green", font=("Arial", 50)) clicked[c * 3 + d] = "O" check() def check(): if (clicked[0] == "X" and clicked[1] == "X" and clicked[2] == "X") or \ (clicked[3] == "X" and clicked[4] == "X" and clicked[5] == "X") or \ (clicked[6] == "X" and clicked[7] == "X" and clicked[8] == "X") or \ (clicked[0] == "X" and clicked[4] == "X" and clicked[8] == "X") or \ (clicked[2] == "X" and clicked[4] == "X" and clicked[6] == "X") or \ (clicked[0] == "X" and clicked[3] == "X" and clicked[6] == "X") or \ (clicked[1] == "X" and clicked[4] == "X" and clicked[7] == "X") or \ (clicked[2] == "X" and clicked[5] == "X" and clicked[8] == "X"): messagebox.showinfo("井字棋", "X方获胜!") reset() elif (clicked[0] == "O" and clicked[1] == "O" and clicked[2] == "O") or \ (clicked[3] == "O" and clicked[4] == "O" and clicked[5] == "O") or \ (clicked[6] == "O" and clicked[7] == "O" and clicked[8] == "O") or \ (clicked[0] == "O" and clicked[4] == "O" and clicked[8] == "O") or \ (clicked[2] == "O" and clicked[4] == "O" and clicked[6] == "O") or \ (clicked[0] == "O" and clicked[3] == "O" and clicked[6] == "O") or \ (clicked[1] == "O" and clicked[4] == "O" and clicked[7] == "O") or \ (clicked[2] == "O" and clicked[5] == "O" and clicked[8] == "O"): messagebox.showinfo("井字棋", "O方获胜!") reset() elif clicked.count("X") + clicked.count("O") == 9: messagebox.showinfo("井字棋", "本局平局!") reset() def reset(): global turns turns = 0 for b in buttons_list: for b2 in b: b2.configure(text=" ") for i in range(len(clicked)): clicked[i] = " " for i in range(3): row = [] for j in range(3): button = Button(screen, height=200, width=200, image=pixel, text=" ", compound="c", bg="papaya whip", command=lambda i=i, j=j: click(i, j)) button.grid(row=i, column=j) row.append(button) buttons_list.append(row) screen.mainloop()
内容的提问来源于stack exchange,提问作者Roni
相关产品推荐
相关产品推荐

