【问题标题】:Kivy: AttributeError: 'Label' object has no attribute 'a'Kivy:AttributeError:“标签”对象没有属性“a”
【发布时间】:2019-06-25 04:32:11
【问题描述】:

我制作了一个简单的应用程序,它有两个同时运行的计时器。一个向上计数,另一个向下计数。

我最初尝试在Label下缩进声明“text:str(round(self.a,1))”,并且会出现标题中所述的错误。我现在已经通过调整我的代码解决了这个问题,如下所示(更改是在最后的 .kv 文件部分中进行的):

from kivy.app import App
from kivy.uix.label import Label
from kivy.animation import Animation
from kivy.properties import NumericProperty
from random import randint
from kivy.uix.boxlayout import BoxLayout

class PleaseWork(BoxLayout):
    a = NumericProperty(randint(3,7))
    b = NumericProperty(0)

    def start(self):

        self.anim = Animation(a=0, duration=self.a)
        self.anim &= Animation(b=15, duration=15)
        self.anim.repeat = True
        self.anim.start(self)


class PleaseApp(App):
    def build(self):
        p = PleaseWork()
        p.start()
        return p

if __name__ == "__main__":
    PleaseApp().run()


<PleaseWork>
    orientation: 'vertical'
    text_1: str(round(self.a, 1))
    text_2: str(round(self.b, 1))
    Label:
        text: root.text_1
    Label:
        id: count_up
        text: root.text_2

虽然代码现在做了它应该做的事情,但我的问题是为什么这纠正了错误?我真的不明白为什么这会有所作为?

【问题讨论】:

    标签: python kivy kivy-language


    【解决方案1】:

    问题是变量的作用域,在.kv中至少有以下几种访问元素的方式:

    -id:

    <A>:
       id: a
       property_a: b.foo_property
       <B>: 
           id: b
           property_b: a.bar_property
    

    它用于引用树中的任何节点。

    -self:

    <A>:
        property_a: self.foo_property
        B:
            property_b: self.bar_property
    

    当使用self时,表示同一个节点引用自己,在前面的例子property_b: self.bar_property中指出bproperty_b的属性将取与@987654329相同的值@ ofb 。它与在 python 类中的用途相同。

    -root:

    <A>:
        B:
            property_b: root.bar_property
    
    <C>:
        D:
            property_d: root.bar_property
    

    在引用树的根时使用root,例如property_b: root.bar_property 表示bproperty_b 将与bar_property froma 采用相同的值。在property_d: root.bar_property 的情况下,它表明dproperty_d 将具有与cbar_property 相同的值。


    综合以上,以下也是解决办法:

    1.

    <PleaseWork>
        orientation: 'vertical'
        Label:
            text: str(round(root.a, 1))
        Label:
            id: count_up
            text: str(round(root.b, 1))
    

    2.

    <PleaseWork>
        orientation: 'vertical'
        id: please_work
        Label:
            text: str(round(please_work.a, 1))
        Label:
            id: count_up
            text: str(round(please_work.b, 1))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 2018-04-02
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多