'how to add checkbox to a button in a loop in kivy python

i am trying to add checkboxes to buttons from a loop. i need the checkbox to select the button should incase the user wish to delete a file. each buttons hold a file. here is my code:

Class FolderScreen(Screen):
  def on_enter(self, *args):
    #if self.nd == []:
    objf = mm.Storenote()
    objf.tif(mm.DB.hod)
    for i in range(len(mm.Storenote.ht)):
        self.b = Button(text= (mm.Storenote.ht[i]), font_size = "25sp")
        self.ck = CheckBox()
        self.b.add_widget(self.ck)
        #self.b.background_normal = ""
        self.b.background_color = 0,0,1,1
        self.b.ids =  {"id":mm.Storenote.nid[i]}
        self.b.size_hint=(1, None)
        self.b.size = (dp(370), dp(50))
        self.nd.append(self.b)
        self.b.bind(on_press=self.build_clickk(self.b))
        self.ids.lpl.add_widget(self.b)

The above code only create one checkbox that is position in the middle of the screen and not associated to any button. How to I create the checkboxes with the button in the same loop?



Solution 1:[1]

The code you've provided is not runnable. That's why it's very hard to guess what's going on actually in your code.

However, following is a simple implementation for:

i need the checkbox to select the button should incase the user wish to delete a file. each buttons hold a file...

from kivy.app import runTouchApp
from kivy.properties import (BooleanProperty, StringProperty)
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.checkbox import CheckBox


class CustomButton(BoxLayout):
    selected = BooleanProperty(False)
    text = StringProperty("Check to select/deselect me")

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.btn = Button(text = self.text)
        self.chbox = CheckBox()
        self.chbox.bind(active=self.setter("selected"))
        self.add_widget(self.chbox)
        self.add_widget(self.btn)
        self.bind(text=self.btn.setter("text"))
        
        self.chbox.bind(active=self.observe_change) # This is redundant, just to demonstrate the state-change. You can remove or modify it.


    def observe_change(self, *args):
        v = self.selected
        self.text = "Selected" if v else "Not selected"
        self.btn.background_color = (1, 1-v, 1-v, 1)
        print(self.selected)


runTouchApp(CustomButton())

Now you can add this CustomButton to any widget and remove it depending on its prop. selected.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ApuCoder