Python对象实例缺少属性?

时间:2015-03-07 22:35:12

标签: python tkinter attributes

我正在尝试使用TKinker,但也试图理解面向对象的编程。我一直得到同样的错误,

  

文件" C:/ Users / User / Documents / Python Scripts / tK_Slider.py",第28行,   在getAngle中       print self.scale1.get()AttributeError:App实例没有属性' scale1'

我的代码,

from Tkinter import *

class App:

    def __init__(self, master):

        frame = Frame(master)
        frame.pack()

        self.scale1 = Scale(master, from_=0, to=180, command=self.getAngle(1))
        self.scale1.pack(side=LEFT)
        self.scale2 = Scale(master, from_=0, to=180, command=self.getAngle(2))
        self.scale2.pack(side=LEFT)
        self.scale3 = Scale(master, from_=0, to=180, command=self.getAngle(3))
        self.scale3.pack(side=LEFT)
        self.scale4 = Scale(master, from_=0, to=180, command=self.getAngle(4))
        self.scale4.pack(side=LEFT)

    def getAngle(self, slider):
        if slider==1:
            print self.scale1.get()
        if slider==2:
            print self.scale2.get()            
        if slider==3:
            print self.scale3.get()
        if slider==4:
            print self.scale4.get()

root = Tk()
app = App(root)
root.mainloop()

我在这里误解了什么?

在我尝试查询其值之前,我认为我已经创建了属性 scale1 ,那么为什么它不会延续到 getAngle()

1 个答案:

答案 0 :(得分:4)

这会立即调用self.getAngle,此时self.scale1尚未设置。

self.scale1 = Scale(master, from_=0, to=180, command=self.getAngle(1))

您需要使用lambda函数进行间接寻址:

self.scale1 = Scale(master, from_=0, to=180, command=lambda ev: self.getAngle(1))