Skip to content Skip to sidebar Skip to footer

Kivy: Manipulating Dynamically Created Widgets In Update Function

I am trying to extend the code in the answer here provided by Nykakin where widgets are defined on the fly in Kivy, dynamically assigned IDs, and then manipulated based on ID. The

Solution 1:

children = MyWidget.children[:]

MyWidget is the class itself, not an instance of it, and so the children is a ListProperty object and not the actual list you want.

You want instead the children of the MyWidget instance that is your root widget, self.root.children.

Also, you clock schedule the update function at class level; I think this is bad practice, and could lead to subtle bugs. It would be more normal to do it in the __init__ method of the widget instead.

Solution 2:

So putting the update function within the 'MyWidget' class and then accessing elements within 'MyWidget' by calling self.children worked!

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.stacklayout import StackLayout
from kivy.uix.button import Button 
from kivy.uix.label import Label 
from kivy.clock import Clock
from kivy.factory import Factory

classMyWidget(BoxLayout):
    def__init__(self, **kwargs):
        super().__init__(**kwargs)

        button = Button(text="Print IDs", id="PrintIDsButton")
        button.bind(on_release=self.print_label)
        self.add_widget(button)

        # crate some labels with defined IDsfor i inrange(5):
            self.add_widget(Button(text=str(i), id="button no: " + str(i)))

        # update moved as per inclement's recommendation
        Clock.schedule_interval(self.update, 1 / 5.0)

    defprint_label(self, *args):
        children = self.children[:]
        while children:
            child = children.pop()
            print("{} -> {}".format(child, child.id))
            # Add smiley by ID
            children.extend(child.children)
            if child.id == "PrintIDsButton":
                child.text = child.text + " :)"defupdate(self, *args):
        children = self.children[:]
        while children:
            child = children.pop()
            # remove smiley by IDif child.id == "PrintIDsButton":
                child.text  = "Print IDs"classMyApp(App):
    defbuild(self):
        return MyWidget()

if __name__ == '__main__':
    MyApp().run()

Thanks again to inclement!

Post a Comment for "Kivy: Manipulating Dynamically Created Widgets In Update Function"