我的应用如下3个步骤:Kivy:如何检索蟒
- 在步骤1中,用户输入一个数字(所有部件都处于
.kv
文件 - 如下面的代码)。 - 在步骤2中,生成了与步骤1中输入的编号一样多的标签和复选框。然后用户选择一些复选框并点击“确定2”按钮(因为第二步的部件数量可能会有所不同,所以它们在
.py
中创建 - 这可能不是最好的方法,但我没有' t找到了一个更好的主意)。 - 在步骤3中,我获得了步骤2中生成的复选框的活动状态,并根据哪一个复选框处于活动状态,我会执行更多步骤。
我的问题是如何获得复选框的状态?当他们被“创建”时,每个人都有一个ID,但是当我打印self.ids
时,这些ID不会出现。如果我将任何参数传递给getcheckboxes_active
def,我也会得到一个错误。 (无法调用)。
的.py
:
import kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.checkbox import CheckBox
from kivy.uix.button import Button
from kivy.properties import StringProperty
class MyWidget(BoxLayout):
input_text = StringProperty("10")
def show(self, number):
layout = BoxLayout(padding=10, orientation="vertical")
for each in range(int(number)):
layout2 = BoxLayout(padding=10, orientation="horizontal")
l=Label(bold= True,font_size=20, text='Hello', markup = True)
c= CheckBox(id = "CheckBox"+str(each))
layout2.add_widget(l)
layout2.add_widget(c)
layout.add_widget(layout2)
button = Button(text="OK 2")
button.bind(on_press=self.getcheckboxes_active) # self.getcheckboxes_active(self, "test") give an error None is not callable
layout.add_widget(button)
self.add_widget(layout)
self.input_text = "Done"
def getcheckboxes_active(self, *arg):
'''how to get the active state of all checkboxed created in def show'''
print(self.ids) # CheckBoxes id aren't displayed
print(*arg)
print("State of all checkboxes")
class MyApp_auto(App):
def build(self):
return MyWidget()
MyApp_auto().run()
的.kv
:我需要有一个.kv因为“第1步中真正的应用程序”是远远比TextInput和一个按钮更加复杂。
<MyWidget>
orientation: "horizontal"
TextInput:
text: root.input_text
id:input
Button:
text:'OK 1'
on_press: root.show(input.text)
非常感谢!即使'print(self.check_ref)'不打印一个'self.check_ref [CheckBox0] .state',我得到错误'name'CheckBox0'未定义' 'CheckBox0'编号。 – Enora
'CheckBox0'应该是一个字符串是吗? – ODiogoSilva
对不起!最后一个问题。为什么这个属性是'state',两个值是'normal'和'down',而对于'.kv'中的一个复选框,属性是'active',值是'True'和'False'? – Enora