在类(OOP)中实现tkinter框架时遇到问题[AttributeError:type对象“Frame”没有属性“tk”]

2024-09-29 19:23:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用Python编写一个扫雷游戏。我创建了一个名为Cell的类,它本质上是一个tkinter框架对象和一个放置在框架中的按钮对象(这样按钮形状就成了正方形)

我在为这个类编写初始值设定项时遇到问题。到目前为止,我试过了

def __init__(self, i, j):
    self.n = i*w+j
    Frame(root, height=50, width=50)
    Frame.grid(row=i, column=j)
    Frame.grid_propagate(0)  
    Frame.columnconfigure(0, weight=1) 
    Frame.rowconfigure(0, weight=1)  
    Button(Frame, width=50, height=50, command=self.find_numbers())

其中find_编号稍后定义。然后我创建C0,Cell的一个实例。但是,我收到了以下错误消息:

Traceback (most recent call last):
  File "C:/Users/ssbol/Documents/Python Scripts/Minesweeper.py", line 56, in <module>
    C0 = Cell(0,0)
  File "C:/Users/ssbol/Documents/Python Scripts/Minesweeper.py", line 40, in __init__
    Frame.grid(row=i, column=j)
TypeError: grid_configure() missing 1 required positional argument: 'self'

我不知道如何修复它,所以我试着胡闹,把Frame换成self.Frame

def __init__(self, i, j):
    self.n = i*w+j
    self.frame = Frame(root, height=50, width=50)
    self.frame.grid(row=i, column=j)
    self.frame.grid_propagate(0)  
    self.frame.columnconfigure(0, weight=1) 
    self.frame.rowconfigure(0, weight=1)  
    self.button = Button(Frame, width=50, height=50, command=self.find_numbers())

这一次,我收到了以下错误消息:

Traceback (most recent call last):
  File "C:/Users/ssbol/Documents/Python Scripts/Minesweeper.py", line 56, in <module>
    C0 = Cell(0,0)
  File "C:/Users/ssbol/Documents/Python Scripts/Minesweeper.py", line 44, in __init__
    self.button = Button(Frame, width=50, height=50, command=self.find_numbers())
  File "C:\Users\ssbol\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 2369, in __init__
    Widget.__init__(self, master, 'button', cnf, kw)
  File "C:\Users\ssbol\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 2292, in __init__
    BaseWidget._setup(self, master, cnf)
  File "C:\Users\ssbol\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 2262, in _setup
    self.tk = master.tk
AttributeError: type object 'Frame' has no attribute 'tk'

我想我有点不知所措,不太明白这些错误信息意味着什么。有人能解释一下这些是什么意思和/或提供解决方案吗?谢谢大家!


Tags: inpyselfinittkinterlinecellwidth

热门问题