[英]Kivy KV File Custom Property
我一辈子都想不通如何通过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()
我想我知道了。 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()
尝试将其打印在即将到来的帧上,而不是在对象启动时进行打印。
创建对象后,您可以访问属性。
您可以通过Clock做到这一点。 像这样:
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.