AttributeError:'int'对象没有属性Python

时间:2014-09-23 05:29:29

标签: python tkinter figure

我不知道为什么我会收到这个错误,这真的很烦人......有人看到了这个问题吗? 我收到这个错误:

 line 66, in <module>
    ting.movefigure(ting, "up", 20)
    AttributeError: 'int' object has no attribute 'movefigure'

这是我的代码:

from tkinter import * import time


def movefigure(self, direction, ammount):
    x = 0
    y = 0
    ammount2 = 0

    if direction == "up":
        print("Direction = " + ammount)
        y = ammount
    elif direction == "down":
        print("Direction = " + ammount)
        ammount2 = ammount - (ammount * 2)
        y = ammount2
    elif direction == "right" + ammount:
        print("Direction = " + ammount)
        x = ammount
    elif direction == "left":
        print("Direction = " + ammount)
        ammount2 = ammount - (ammount * 2)
        y = ammount2
    canvas.move(self, x, y)


root = Tk()

root.title('Canvas')

tingx = 100 
tingy = 100

tingxMove = 1 
tingyMove = 1

canvas = Canvas(root, width=400, height=400) 
ting = canvas.create_rectangle(205, 10, tingx, tingy, tags="Ting", outline='black', fill='gray50')

canvas.pack()

ting.movefigure(ting, "up", 20) 
root.mainloop()

1 个答案:

答案 0 :(得分:1)

你正在混淆功能和方法。

方法是在类中定义的函数;它需要一个self参数,并在该类的实例上调用它。像这样:

class Spam(object):
    def __init__(self, eggs):
        self.eggs = eggs
    def method(self, beans):
        return self.eggs + beans

spam = Spam(20)
print(spam.method(10))

这将打印出30


但是你的movefigure不是任何类的方法,它只是一个常规函数。这意味着它不会使用self参数,也不会使用点语法调用它。 (当然,如果你愿意,没有什么停止你调用任何参数self,就像没有什么能阻止你编写一个名为print_with_color的函数来删除一个名为{{的文件1}},但这不是一个好主意......)


所以,你想这样做:

/kernel