問題描述
好吧,假設我希望某個小部件中的標簽使用另一個小部件內標簽中的文本:
Ok let's say I want that label in some widget to use text from label inside another widget:
<SubWidget@RelativeLayout>:
Label:
text: str(root.parent.ids.first.text)
<RootWidget>:
Label:
id: first
center_x: 100
text: "text"
SubWidget:
id: second
center_x: 200
這可行,但似乎不是很好的解決方案.如果我將 first
放在另一個小部件中,我需要在代碼中的任何地方更改對它的引用(這可能導致錯誤).
This works but doesn't seem to be nice solution. If I'll place first
inside another widget I'll need to change reference to that it everywhere in the code (that can lead to errors).
我的第一個想法是至少在根級別存儲對 first
的引用并對其進行引用:
My first idea was at least to store reference to first
at root level and reference to it:
<SubWidget@RelativeLayout>:
Label:
text: str(root.parent.l.text)
<RootWidget>:
l: first
Label:
id: first
center_x: 100
text: "text"
SubWidget:
id: second
center_x: 200
但這會導致異常:
AttributeError: 'NoneType' object has no attribute 'text'
這很令人困惑,因為如果我寫類似 text: str(root.parent.l)
我會看到 Label object
而不是 NoneType
.
This is confusing since if I'll write something like text: str(root.parent.l)
I'll see Label object
rather than NoneType
.
所以我有兩個問題:
- 為什么第二種解決方案不起作用?如何解決?
- 一般來說,從另一個小部件訪問某些小部件屬性的最佳方式是什么?我可以讓它獨立于小部件層次結構嗎?
推薦答案
對象屬性
l
可能會在第一次事件循環迭代之后 被填充,而您正試圖在第一次迭代中訪問它.您可以將其延遲到第二次迭代以使其正常工作.
The object property
l
probably gets populated after the first event loop iteration, while you are trying to access it within the first. You could delay it till the second iteration to make it work.
最強大的方法是從 python 代碼中綁定這些屬性,但是有一些 kv lang 技巧可以使其更簡單.這是我最喜歡的方法:
The most powerful approach is to bind those properties from inside python code, but there are some kv lang tricks to make it simpler. This is my favorite method:
BoxLayout
Label
id: label
text: 'hello world'
SubWidget
label_text: label.text
<SubWidget@BoxLayout>
label_text: 'none'
Label
text: root.label_text
這篇關于如何從 Kivy 中的另一個小部件訪問某些小部件屬性?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!