Kivy:属性错误:"标签"对象没有属性"a"



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

我最初尝试说明"文本:str(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

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

问题是变量的范围,在.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的属性将与bbar_property相同。它具有与python类相同的用途。

-root

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

在引用树的根时使用root,例如property_b: root.bar_property指示bproperty_b将从a中获得与bar_property相同的值。在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))

最新更新