2014-09-23 89 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) 
相關問題