我一辈子都想不出如何通过 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/