如何在类的__init__函数中使用canvas参数?

时间:2016-12-28 15:35:00

标签: python tkinter

我制作了一个名为gamesmodule的模块,我正在制作一个程序,使球在画布上生成并反弹。我用过

class Ball:
    def __init__(self, canvas):
        self.canvas = canvas
        self.id = canvas.create_oval(10, 10, 25, 25, fill='red')
        self.canvas.move(self.id, 25, 25)
        self.x = 0
        self.y = -1
        self.canvas_height = self.canvas.winfo_height
        self.canvas_width = self.canvas.winfo_width

并且init函数包含canvas参数,用于输入画布名称。我已经预定了画布,并在课堂上创建了球:

ball = Ball(canvas)

但是Python shell输出了这个错误:

 Traceback (most recent call last):
 File "<pyshell#59>", line 1, in <module>
 ball = Ball(canvas)
 NameError: name 'canvas' is not defined

2 个答案:

答案 0 :(得分:1)

Python使用空格(缩进)来定义代码块的限制。您需要对齐__init__中的所有行:

class Ball:
    def __init__(self, canvas):
        self.canvas = canvas
        # Lines below this one were unindented in your example:
        self.id = self.canvas.create_oval(10, 10, 25, 25, fill='red')
        self.canvas.move(self.id, 25, 25)
        self.x = 0
        self.y = -1
        self.canvas_height = self.canvas.winfo_height
        self.canvas_width = self.canvas.winfo_width

但是,这不会产生您的错误。看一下描述:

ball = Ball(canvas)
NameError: name 'canvas' is not defined

在您调用canvas的块中未定义变量Ball(canvas)。 Python不知道canvas在该上下文中的含义。

答案 1 :(得分:0)

您必须定义canvas

canvas = tkinter.Canvas(...)

ball = Ball(canvas)

也许你在错误的地方定义canvas - 即。在某些功能中 - 当您执行Ball(canvas)

时,它不可用