【问题标题】:Kivy KV File Custom PropertyKivy KV 文件自定义属性
【发布时间】:2018-11-04 17:16:37
【问题描述】:

我终生无法弄清楚如何通过 KV 文件在自定义小部件上传递自定义属性。我的应用程序是一个包含 Button() 和 TestWidget() 的简单网格。 TestWidget() 有一个 StringProperty() test_property,它似乎没有从 KV 文件中获取数据,正如 init 上的 print 语句所见。这里有一些快速直接的代码作为示例。

谢谢。

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()

【问题讨论】:

    标签: python properties kivy


    【解决方案1】:

    我想我明白了。 Kivy 不会将任何东西传递给对象。我在https://kivy.org/docs/api-kivy.properties.html 学到了这一点。

    我使用 on_ 来做需要做的事情。 Kivy 对象和 Python 对象之间有很大的区别。

    这是一个自定义 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()
    

    【讨论】:

      【解决方案2】:

      尝试在即将到来的帧上打印它,而不是在对象的初始化中。
      创建对象后,您可以访问属性。
      你用时钟做到这一点。 像这样:

      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-16
        • 2016-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多