如何在kv lang中重用这些代码?
<Search_type_panel>:
max1_optn: max1
max2_optn: max2
both_optn: both
BoxLayout:
padding: "10dp"
orientation: 'vertical'
BoxLayout:
orientation: 'horizontal'
CheckBox:
id: max1
active: True
group: 'search_type'
Label:
text: "[ref=max1]max1[/ref]"
size_hint_x: "10"
markup: True
on_ref_press: root.setstatus(max1)
CheckBox:
id: max2
active: False
group: 'search_type'
Label:
text: "[ref=max2]max2[/ref]"
size_hint_x: "10"
markup: True
on_ref_press: root.setstatus(max2)
CheckBox:
id: both
active: False
group: 'search_type'
Label:
text: "[ref=both]both[/both]"
size_hint_x: "10"
markup: True
on_ref_press: root.setstatus(max2)
正如您所看到的,Label和Checkbox可以是一个分组的复合面板,我必须为每个参数提供不同的参数,因此从长远来看,维护很简单,但如何将新参数传递给这些人呢?虽然我知道我可以将它们分组为:
<custom>:
CheckBox:
id: both
active: False
group: 'search_type'
Label:
text: "[ref=both]both[/both]"
size_hint_x: "10"
markup: True
on_ref_press: root.setstatus(max2)
我真的不知道如何将新参数传递给小部件并重用kv lang代码。
答案 0 :(得分:1)
由于每个 CheckBox 都有不同的 有效值 ( True 或 False ),不建议创建包含 CheckBox 和 Label 的动态类,因为很难引用CheckBox并分配不同的 id 当它们被实例化为孩子时,em> 和 活动值 到每个人。
<Custom>:
CheckBox:
active: False
group: 'search_type'
Label:
size_hint_x: "10"
markup: True
on_ref_press: app.root.setstatus(self)
下面的示例分别为CheckBox和Label创建了两个动力类。
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
class Search_type_panel(BoxLayout):
max1_optn = ObjectProperty(None)
max2_optn = ObjectProperty(None)
both_optn = ObjectProperty(None)
def setstatus(self, label):
print("\nsetstatus:")
for key in label.refs:
print("\tUser clicked on refs =", key)
class TestApp(App):
def build(self):
return Search_type_panel()
if __name__ == "__main__":
TestApp().run()
#:kivy 1.10.0
<CustomCheckBox@CheckBox>:
active: False
group: 'search_type'
<CustomLabel@Label>:
size_hint_x: "10"
markup: True
on_ref_press: app.root.setstatus(self)
<Search_type_panel>:
max1_optn: max1
max2_optn: max2
both_optn: both
BoxLayout:
padding: "10dp"
orientation: 'vertical'
BoxLayout:
orientation: 'horizontal'
CustomCheckBox:
id: max1
active: True
CustomLabel:
text: "[ref=max1]max1[/ref]"
CustomCheckBox:
id: max2
CustomLabel:
text: "[ref=max2]max2[/ref]"
CustomCheckBox:
id: both
CustomLabel:
text: "[ref=both]both[/ref]"