【问题标题】:Grid of button objects with row and col attributes using Tkinter. AttributeError: 'Buttons' object has no attribute 'tk'使用 Tkinter 的具有 row 和 col 属性的按钮对象网格。 AttributeError: \'Buttons\' 对象没有属性 \'tk\'
【发布时间】:2022-11-12 10:59:29
【问题描述】:

制作像 tic tac toe 这样的棋盘大小可调的游戏。我需要在单击时更改按钮的文本,因此我试图使按钮对象具有 row 和 col 属性。第一次使用任何 GUI,所以如果我做错了,我深表歉意。

import tkinter as tk
from tkinter import*

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(str(board_size*50)+"x"+str(board_size*50))
    
class Buttons():
    def __init__(self, root):
        self.buttons = {}
    def create_button(self, x, y):
        button = tk.Button(self, text = " ")
        button.grid(row = x, column = y)
        self.buttons[(x,y)] = button
    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()

错误:

AttributeError:“按钮”对象没有属性“tk”

【问题讨论】:

  • self 不包含对 tkinter.Widget 的引用,因此它没有属性 tk 也就不足为奇了。您可以在这里省略主控 button = tk.Button(text = " ") 或使用 tkinter.Widget 实例。
  • 嗯,我现在感觉很笨。谢谢!!!
  • 嗯,这就是我每天的感受 :DD 继续学习 :)

标签: python tkinter attributeerror


【解决方案1】:

我遇到了和你一样的问题。我在第 25 行发现了问题。

改变这个:

button = tk.Button(self, text = " ")

至:

button = tk.Button(root, text = " ")

输出:

【讨论】:

    猜你喜欢
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 2021-11-22
    • 1970-01-01
    相关资源
    最近更新 更多