如何在Kivy中使用TreeView?

时间:2018-01-13 17:53:35

标签: python treeview kivy

我想要一个需要在主菜单上使用TreeView的应用程序。我想在TreeView中单击按钮添加节点。当我单击按钮将节点添加到树视图时,我收到错误。 (我试图发现TreeView小部件,但即使使用文档我也无法实现它)

gui_test.py:

import kivy
kivy.require('1.10.0')

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen, ScreenManager

class UI(ScreenManager):
    def __init__(self, **kwargs):
        super(UI, self).__init__(**kwargs)

class Screen1(Screen):
    def __init__(self, **kwargs):
        super(Screen1, self).__init__(**kwargs)


Builder.load_file("gui_test.kv")

class MyApp(App):
    def build(self):
        return UI()

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

gui_test.kv:

#: kivy 1.10.0

<UI>:
    Screen1:
        name: "screen1"

        BoxLayout:

            TreeView:
                id: tv

            Button:
                size: (200, 50)
                size_hint: (None, None)
                text: "add_node"
                on_press: tv.add_node(TreeViewLabel(text = "Node..."))
单击按钮时

输出错误:

(...)
File "kivy\_event.pyx", line 714, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:8146)
   File "kivy\_event.pyx", line 1225, in kivy._event.EventObservers.dispatch (kivy\_event.c:14035)
   File "kivy\_event.pyx", line 1109, in kivy._event.EventObservers._dispatch (kivy\_event.c:12816)
   File "C:\Users\hnnc\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 64, in custom_callback
     exec(__kvlang__.co_value, idmap)
   File "C:\Users\hnnc\Documents\Interpreter\GUI_TEST\gui_test.kv", line 16, in <module>
     on_press: tv.add_node(TreeViewLabel(text = "Node..."))
 NameError: name 'TreeViewLabel' is not defined

1 个答案:

答案 0 :(得分:1)

您的代码是正确的,您只需要在您的kv文件中import TreeViewLabel类:

#: kivy 1.10.0
#: import TreeViewLabel kivy.uix.treeview.TreeViewLabel


<UI>:
    Screen1:
        name: "screen1"

        BoxLayout:

            TreeView:
                id: tv

            Button:
                size: (200, 50)
                size_hint: (None, None)
                text: "add_node"
                on_press: tv.add_node(TreeViewLabel(text = "Node..."))