2014-09-23 200 views
-3

我不知道为什么我得到这个错误,这真的很烦人......任何人都看到这个问题? 我得到这个错误:AttributeError:'int'对象没有属性Python

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() 
+0

如何婷movefigure有关。 movefigure是单独的方法不属于ting – 2014-09-23 05:34:03

+0

我认为当你这样做时,它会把第一个对象(ting)作为参数中的自我? 那我该怎么做呢? – RasmusGP 2014-09-23 05:35:42

+0

只是删除丁。并运行移动图形(ting,“up”,20) – 2014-09-23 05:35:49

回答

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函数删除一个名为/kernel文件阻止你,但它不是一个好主意......)


所以,你想做到这一点:

def movefigure(rect, direction, ammount): 
    # all of your existing code, but using rect instead of self 

movefigure(ting, "up", 20) 
相关问题