使用Tkinter创建带行列属性的按钮网格时遇AttributeError错误
错误原因
你的Buttons类创建按钮时,把self(Buttons类的实例)传给了tk.Button的第一个参数(父组件位置),但Tkinter组件要求父组件必须是Tkinter的窗口/容器对象(比如root),而Buttons实例并非Tkinter组件,自然没有tk属性,因此触发报错。
修复后的完整代码
import tkinter as tk def create_board(board_size): board = [] for x in range(board_size): row = [] for col in range(board_size): row.append("") board.append(row) return board board_size = 12 board = create_board(board_size) root = tk.Tk() root.geometry(f"{board_size*50}x{board_size*50}") class Buttons(): def __init__(self, root): self.root = root # 保存父窗口引用 self.buttons = {} self.current_player = "X" # 用于切换玩家标识 def create_button(self, x, y): # 按钮父组件改为保存的root,绑定点击事件实现文本切换 button = tk.Button(self.root, text=" ", width=3, height=1, command=lambda x=x, y=y: self.on_button_click(x, y)) button.grid(row=x, column=y, padx=2, pady=2) self.buttons[(x,y)] = button def on_button_click(self, x, y): # 点击时更新按钮文本,交替切换X/O if board[x][y] == "": board[x][y] = self.current_player self.update_button(x, y, self.current_player) self.current_player = "O" if self.current_player == "X" else "X" def update_button(self, x, y, letter): self.buttons[(x,y)].configure(text=letter) app = Buttons(root) for x in range(board_size): for col in range(board_size): app.create_button(x, col) root.mainloop()
关键修改说明
- 在
Buttons类的__init__方法中新增self.root = root,将传入的父窗口保存为实例属性,为按钮提供合法的父组件 - 创建
tk.Button时,将第一个参数从self改为self.root,指定正确的父组件 - 新增
on_button_click方法,实现点击按钮切换文本(X/O交替)的核心功能,满足你点击改文本的需求 - 优化了按钮的大小和间距,让棋盘显示更规整
内容的提问来源于stack exchange,提问作者Claudia St. John
相关产品推荐
相关产品推荐

