【问题标题】:Python keeps showing 'object has no such attribute'Python 不断显示“对象没有这样的属性”
【发布时间】:2019-06-14 23:15:43
【问题描述】:

由于某种原因,在执行以下代码行时,出现错误说明:'car' object has no attribute 'time_int' Class is called car。

虽然我已经将方法包含在同一个类中,但每次尝试调用self.time_int都会出现上述错误,以下是代码片段:

# the __init__ also has the buttons that connect to other methods, but I just included the relevant one

    class car:


    def __init__(self,master):

        self.helv = tkinter.font.Font(family ="Helvetica", size = 20, weight = 'bold')

        self.master = master

        master.title('RC car controls')
        self.background_image = PhotoImage(file='1.gif') #upload background picture
        self.background_label = Label(master, image=self.background_image)
        self.background_label.image = self.background_image
        self.background_label.place(x=0,y=0,relwidth=1, relheight=1) #placing of background picture
        master.geometry("500x500")
        master.resizable(0, 0)

        self.acl = Button(master, command = lambda:    [self.set_down(),self.set_up()], image = self.img,
                      padx = 4, pady = 4)
        self.acl.place(relx = 0.7, rely = 0.5)


    def set_down(self):
        self.acl.bind('<Button-1>', self.accel_gn)


    def set_up(self):
        self.acl.bind('<ButtonRelease-1>',self.accel_fn)

    def accel_fn(self,accel_fn):  ##### ACCELERATION SLOWS DOWN
        self.start = time()
        print('up')
        self.time_int = (self.start-self.end)
        print(self.time_int)

    def accel_gn(self,accel_gn): ##### ACCELERATION INCREASES
        self.end = time()
        a = speed()
        print('down')
        if 1 > self.time_int > 0:
            print('current motor speed:', a.final_speed())

第二个方法accel_gn(self,accel_gn)在if语句的那一行出现错误。为了澄清,该按钮基本上检查它被按下了多长时间并调用另一个名为 final_speed() 的类中的方法。

谢谢

编辑:当我在空闲状态下第二次按下按钮时,它只是继续运行并且错误不会停止它。该错误仅在第一次单击按钮时弹出。

【问题讨论】:

  • 能把这个类的__init__方法的实现贴出来吗?
  • 事实上,完整的定义是最理想的——您可以编辑您的问题以创建一个minimal reproducible example 来显示实际问题。

标签: python tkinter compiler-errors


【解决方案1】:

我认为您需要在accel_gn 中定义self.time_int

【讨论】:

  • 使用与accel_fn 中的值相同的值或其他值来定义它?
  • 相同的值。
  • 好吧,刚刚试了一下,将其定义为self.time_int = (self.start-self.end) 现在给我错误:AttributeError: 'car' object has no attribute 'start'
  • 是的,因为start 在另一个函数中 --accel_fn。您必须从那里访问该信息
猜你喜欢
  • 2013-04-20
  • 2018-05-01
  • 1970-01-01
  • 2020-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-12
  • 1970-01-01
相关资源
最近更新 更多