Search code examples
pythonkivytreeview

How to initialize a Kivy TreeView on GUI-init?


I am trying to realize a dynamic TreeView where all updates are initialized in kivy and call a function called populate_tree_view(self, tree). The available Tree-View-docs have been a bit cryptic to me regarding this approach...I already fail at filling a TreeView on init of the App. For the following code I get the error:

name "wid" is not defined

How is that possible? As far as I understand, I refer to self=Widget, and this widget has a TreeView called "wid". Please help me.

My kivi file:

<Widget>
  TreeView:
    id: wid
    root_options: dict(text=somename)

my python code:

class Widget(StackLayout):

    def populate_tree_view(self, tree):
        self.wid.add_node(TreeViewLabel(text='My first item'))
        print("done")

# Init GUI
class App (App):
    def build(self):
        App = Widget()
        App.populate_tree_view(tree)
        return App

App().run()

Solution

  • Several issues:

    • You need to use Clock.schedule_once() to call your populate_tree_view() method. That will delay the call until the wid is is available in the ids. Put the Clock.schedule_once() in the build() method just before the return.
    • To access wid you must use the ids dictionary (self.ids.wid.add_node(TreeViewLabel(text='My first item'))
    • App is a class in the Kivy package. Redefining it as a Widget instance (or even as the name of your App class) is a bad idea. Just don't set App = to anything and don't use class App():.