vendredi 3 mars 2017

Kivy: how to retrieve ids or active states of checkbox (or other widgets) created within python

My app follows 3 steps:

  • In step 1, the users enter a number (all widgets are in a .kv file -cf the code below).
  • In step 2, as many labels and checkboxes as the number entered in step 1 are generated. Then the user select some checkboxes and click on the button "OK 2".(Because the number of widgets of the second step can vary,they are created in the .py ―it may not be the best way to do it but I haven't found a better idea).
  • In step 3, I get the active state of the checkboxes generated in step 2 and according to which one is active or not, I do some more steps.

My question is how can I get the state of the checkboxes? When they are "created", each has an id but these ids don't appear when I print self.ids. Also I get an error if I pass any argument to the getcheckboxes_active def. (None is not callable).

The .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()

The .kv: I need to have a .kv because the "step 1 real app" is way more complex than an TextInput and a Button.

<MyWidget>
    orientation: "horizontal"
    TextInput:
        text: root.input_text
        id:input
    Button:
        text:'OK 1'
        on_press: root.show(input.text)




Aucun commentaire:

Enregistrer un commentaire