[英]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.