我正在創建一個kivy用戶界面來顯示由我寫爲標準python對象的數據模型生成的值。實質上,我希望用戶能夠按下一個按鈕,這會改變底層的數據模型,並且這個更改的結果會自動更新和顯示。這是我的理解,這可以使用kivy屬性(在這種情況下,ObjectProperty)實現。Kivy ObjectProperty來更新標籤文本
下面是一些示例代碼:
import kivy
kivy.require('1.7.0')
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.properties import ObjectProperty
from kivy.lang import Builder
Builder.load_string("""
<RootWidget>:
cols: 2
Label:
text: "Attribute a:"
Label:
text: root.data_model.a
Label:
text: "Attribute b:"
Label:
text: root.data_model.b
Label:
text: "Attribute c:"
Label:
text: root.data_model.c
Button:
text: "Make data_model.a longer"
on_press: root.button_press()
Button:
text: "Make data_model.b shorter"
on_press: root.button_press2()
""")
class DataModel(object):
def __init__(self):
self.a = 'This is a'
self.b ='This is b'
@property
def c(self):
return self.a + ' and ' + self.b
class RootWidget(GridLayout):
data_model = ObjectProperty(DataModel())
def button_press(self, *args):
self.data_model.a = 'This is a and it is really long now'
print self.data_model.c
def button_press2(self, *args):
self.data_model.b = 'B'
print self.data_model.c
class TestApp(App):
def build(self):
return RootWidget()
app = TestApp()
app.run()
期望的結果是,用於當用戶按下任一按鈕時,標籤會自動更新以顯示新的屬性。從print語句可以看出,data_model得到了正確的更新。但是,沒有任何標籤正在更新。有人可以澄清如何做到這一點?
這是一個好主意,但我的具體的問題可能很難,因爲'''self.bind(A = self.set_c)'''部分來實現。具體來說,我的數據模型有一套非常複雜的內部關係,並將10個輸入變量映射到30-40個輸出變量的數量比我希望我必須要做的要多。無論如何,謝謝你的想法。 – jsexauer
你能指點我一些關於AliasProperty的東西嗎?我發現kivy文檔對於它的工作原理以及它的目的有點缺乏。 – jsexauer
AliasProperty不對應於單個屬性,但實際上是一對在設置或訪問時調用的函數。這些可能會訪問或修改其他屬性,如普通的python屬性。 – inclement