'how to clear buttons created in a loop from a boxlayout

i have a folderscreen that displays buttons from a loop, the buttons have title of the files saved, when i click the buttons, it opens a new page that shows the content of the file, but when i go back to the folder screen, 2 sets of the button in the loop are added to the existing buttons. what i want is everytime i leave the folderscreen, i want the buttons cleared, so that when i go back, it will run the loop code again and shows only the buttons from the loop without repetition. or may be there is a way i can stop the loop code from running if the boxlayout that house the buttons is not empty. here is my code:

    def on_enter(self, *args):
    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.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.b.bind(on_press=self.build_clickk(self.b))
        self.ids.lpl.add_widget(self.b)

        #self.ids.lpl.add_widget(self.l[i])

def build_clickk(self, b):
    def clickk(*args):
        ci = b.ids.id
        print(ci)
        objff = mm.Show()
        objff.getter(ci)
        self.manager.current = "Readpage"
    return clickk
def on_leave(self, *args):
    self.ids.lpl.remove_widget(self.b)

the def on_leave function only remove one of the buttons and add 2 new sets of the button each time i go back to the folderscreen



Solution 1:[1]

You can use self.ids.lpl.clear_widgets() right before your for-loop. This way you ensure that the layout is empty before adding new widgets.

If you add many widgets, try using def on_pre_enter(). kivy will render the widgets before entering the screen and this may prevent "flickering" when building all widgets.

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 guti