简体   繁体   English

Kivy KV文件自定义属性

[英]Kivy KV File Custom Property

I cannot for the life of me figure out how to pass a custom property on a custom widget via the KV file. 我一辈子都想不通如何通过KV文件在自定义小部件上传递自定义属性。 My application is a simple grid that contains a Button() and TestWidget(). 我的应用程序是一个简单的网格,其中包含Button()和TestWidget()。 TestWidget() has a StringProperty() test_property that doesn't seem to get the data from the KV file as seen by the print statement on init. TestWidget()的StringProperty()test_property似乎没有从KV文件中获取数据,如init上的print语句所示。 Here's some quick straight forward code as an example. 这里有一些快速简单的代码作为示例。

Thanks. 谢谢。

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.properties import StringProperty


Builder.load_string("""
<TestWidget>:

<TestGrid>:
    Button:
    TestWidget:
        test_property: 'Test Property'
""")


class TestWidget(Widget):
    test_property = StringProperty()

    def __init__(self, **kwargs):
        super(TestWidget, self).__init__(**kwargs)

        print('Test OUTPUT:', self.test_property)


class TestGrid(GridLayout):
    pass


class MyApp(App):
    def build(self):
        return TestGrid()


MyApp().run()

I think I figured it out. 我想我知道了。 Kivy doesn't pass anything to the objects. Kivy不会将任何东西传递给对象。 I learned this at https://kivy.org/docs/api-kivy.properties.html . 我在https://kivy.org/docs/api-kivy.properties.html上了解了这一点。

I use the on_ to do what needs to be done. 我使用on_做需要做的事情。 There is a big difference between Kivy Objects and Python Objects. Kivy对象和Python对象之间有很大的区别。

Here's an example of a custom BoxLayout; 这是一个自定义BoxLayout的示例;

class KivyInput(BoxLayout):
    text_test = StringProperty()

    def __init__(self, **kwargs):
        super(KivyInput, self).__init__(**kwargs)

        self.orientation = 'horizontal'
        self.label = Label()
        self.text_input = TextInput(multiline=False)
        self.add_widget(self.label)
        self.add_widget(self.text_input)

    def on_text_test(self, instance, value):
        self.label.text = value

    def remove(self):
        self.clear_widgets()

Try printing it on the upcoming frame, instead of in the initiation of the object. 尝试将其打印在即将到来的帧上,而不是在对象启动时进行打印。
After the object is created, you can access the properties. 创建对象后,您可以访问属性。
You do that with Clock. 您可以通过Clock做到这一点。 Like this: 像这样:

from kivy.clock import Clock    

class TestWidget(Widget):
    test_property = StringProperty()

    def __init__(self, **kwargs):
        super(TestWidget, self).__init__(**kwargs)
        Clock.schedule_once(self.after_init) # run method on next frame

    def after_init(self,dt):
        print('Test OUTPUT:', self.test_property)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM