您可以使用其获取复选框的选中状态active
属性,所以尝试更改:
GreenButton:
text: 'Ok'
on_press: root.insert_data(chk.active ,age.text)
在这个片段中chk.text
被改为chk.active
这对我来说很有效。
有关 kivy 复选框的更多参考,请参见https://kivy.org/docs/api-kivy.uix.checkbox.html https://kivy.org/docs/api-kivy.uix.checkbox.html
希望能帮助到你。试一试。
UPDATE:
因此,为了能够获取每个复选框的属性和您可以分配的文本输入ObjectProperties
到小部件,您可以将它们链接到您的test.py
file.
修改后的来源:
test.py
from kivy.uix.screenmanager import Screen
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.properties import ObjectProperty
Window.size = (600, 325)
class UserGroup(Screen):
male = ObjectProperty(None)
female = ObjectProperty(None)
age = ObjectProperty(None)
def insert_data(self):
if self.male.active:
print('Male')
elif self.female.active:
print('Female')
else:
print('No gender selected')
print(self.age.text)
class FactUserGroup(App):
def build(self):
self.root = Builder.load_file('test.kv')
return self.root
if __name__ == '__main__':
FactUserGroup().run()
In the .py
文件你可以找到新的导入ObjectProperty
。
您还可以看到定义了三个新属性UserGroup
与视图交互,以及修改UserGroup.insert_data
很简单。
test.kv
<CustomLabel@Label>:
text_size: self.size
valign: "middle"
padding_x: 5
<SingleLineTextInput@TextInput>:
multiline: False
<GreenButton@Button>:
background_color: 1, 1, 1, 1
size_hint_y: None
height: self.parent.height * 0.120
UserGroup
male: chk_male
female: chk_female
age: txt_age
GridLayout:
cols: 2
padding : 30,30
spacing: 20, 20
row_default_height: '30dp'
Label:
text: 'Male'
text_size: self.size
valign: 'middle'
CheckBox:
group: 'check'
id : chk_male
Label:
text: 'Female'
text_size: self.size
valign: 'middle'
CheckBox:
group: 'check'
id: chk_female
CustomLabel:
text: 'age'
text_size: self.size
valign: 'middle'
SingleLineTextInput:
id: txt_age
GreenButton:
text: 'Ok'
on_press: root.insert_data()
GreenButton:
text: 'Cancel'
on_press: app.stop()
In the .kv
文件中两个复选框的 id 和文本输入被重命名为chk_male
, chk_female
and txt_age
分别。
您还可以看到对象属性链接是在开头定义的UserGroup
部分。
希望它有意义并符合您的要求。