【发布时间】:2020-01-14 00:30:09
【问题描述】:
我正在尝试用 Python 编写一个扫雷游戏。我创建了一个名为 Cell 的类,它本质上是一个 tkinter Frame 对象和一个放置在 Frame 中的 Button 对象(这样按钮的形状就是方形的)。
我在编写此类的初始化程序时遇到问题。到目前为止,我试过了
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_numbers 是稍后定义的。然后我创建 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'
我想我有点不知所措,并不真正理解这些错误消息的含义。有人可以解释这些是什么意思和/或提供解决方案吗?谢谢!
【问题讨论】:
-
self.button = Button(Frame,...)。当您应该传递一个实例时,您正在传递Frame类作为self.button的父小部件。将其更改为self.button = Button(self.frame, ...)以继续您的下一个问题,即命令 :)
标签: python python-3.x tkinter