python - Kivy KV 文件自定义属性

标签 python properties kivy

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

谢谢。

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

最佳答案

我想我明白了。 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()

关于python - Kivy KV 文件自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50526939/

相关文章:

Python:Windows 上的 Flask 服务器——如何通过 SSL 验证 Flask Web 服务器?

java - 如何引用资源包?

hibernate - Grails加载属性文件并同时使用dbCreate =“create-drop”

c# - MSBuild 属性引用

python-2.7 - 如何获取 Python 字典值列表并在 Kivy UI 中显示为表格(使用 ListView 小部件)?

python - 如何在django中自定义{% bootstrap_form form %}?

Python 列表追加时间

python - 如何使用python套接字发送TCP FIN

python - 在 Kivy 中使用 jsonstore

python - 如何使用 kivy 中的 glumpy 或 vispy?