【问题标题】:Why I can't access Kivy lang property from __init__?为什么我无法从 __init__ 访问 Kivy lang 属性?
【发布时间】:2021-05-06 20:14:24
【问题描述】:

我是 python 初学者。 我喜欢了解 Kivy 和 Python 的概念。 我不明白为什么下面的代码会出错。

Python 文件

from kivy.app import App
from kivy.uix.button import Button


class MyButton(Button):

    def __init__(self, **kwargs):
        super(MyButton, self).__init__(**kwargs)
        print(f"self.name is{self.name}") #it makes error.

    def print_name(self):
        print(self.name) #But it doesn't make error!!


class TestApp(App):
    def __init__(self, **kwargs):
        super(TestApp, self).__init__(**kwargs)
        self.title = 'Test'


if __name__ == '__main__':
    TestApp().run()
    

Kivy 文件

#:kivy 1.10.0

<MyButton>:
    name: "MyButton"
    on_press: self.print_name()

MyButton:
    text: self.name

我认为 name 属性已经存在,因为它是作为 kivy 文件中的类属性创建的,因此 print_name 方法不会出错。

句子中哪里有错误? 如何在 init 方法中使用 kivy-file 中的名称属性(属性)?

【问题讨论】:

    标签: python properties attributes kivy


    【解决方案1】:

    您无法在__init__() 方法中访问该属性,因为当时尚未创建或设置该属性。在您的kv 中评估&lt;MyButton&gt;: 规则时,将创建和设置该属性。您可以通过稍微延迟访问来访问name 属性。例如,通过使用Clock.schedule_once()

    class MyButton(Button):
    
        def __init__(self, **kwargs):
            super(MyButton, self).__init__(**kwargs)
            # print(f"self.name is{self.name}")  # it makes error.
            Clock.schedule_once(lambda dt: self.print_name())
    
        def print_name(self):
            print(self.name)  # But it doesn't make error!!
    

    【讨论】:

    • 谢谢,它有效!但我想知道何时评估 kivy 规则和顺序。如果你知道的话,请告诉我参考。
    • 一般来说,当你调用Apprun()方法时,会加载kv文件(如果命名正确的话)。 kv 的加载会构建任何指定的根小部件(调用其__init__() 方法),然后应用适用于该小部件的任何规则(由kv 中的&lt;&gt; 指定)。
    猜你喜欢
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多