Kivy添加节点动态到Tree View

2024-10-03 23:28:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在循环中add_nodesTreeView。在

我有一个带有employ信息和指定id的sql数据库。我需要从数据库中添加节点及其名称,并从数据库中为TreeViewButton分配变量id。我还需要将clk方法绑定到添加的节点。在

我该怎么做? 谢谢您!在

到目前为止,我得到的是:

.py文件:

    import sqlite3

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.treeview import TreeView, TreeViewNode
from functools import partial

Builder.load_file("test1.kv")


class TreeViewButton(Button, TreeViewNode):
    id = ""
    def clk(self):
        print(id)

class OrgChart(Screen, TreeViewButton):

    def __init__(self, **kwargs):
        super(OrgChart, self).__init__(**kwargs)
        self.createTree()

    def extractNames(self):
        cur = sqlite3.connect('QLA_491.s3db').cursor()
        query = cur.execute('SELECT * FROM QLA_049P')
        colname = [d[0] for d in query.description]
        result_list = []
        for r in query.fetchall():
            row = {}
            for i in range(len(colname)):
                row[colname[i]] = r[i]
            result_list.append(row)
            del row

        cur.close()
        cur.connection.close()
        print(result_list)
        return result_list

    def createTree(self):
        tv = TreeView()
        for dict in self.extractNames():
            for key, value in dict.items():
                if key == "Button_ID":
                    self.ids.tv.add_node(TreeViewButton())
                    self.id=value
                    self.bind(on_press=self.clk)



sm = ScreenManager()
sm.add_widget(OrgChart())


class MainApp(App):

    def build(self):
        return sm


if __name__ == "__main__":
    MainApp().run()

.kv文件:

^{pr2}$

Tags: infromimportselfaddidfordef
1条回答
网友
1楼 · 发布于 2024-10-03 23:28:49

试试这个:

...

from kivy.properties import StringProperty
...


class TreeViewButton(Button, TreeViewNode):
    #id = ""
    id = StringProperty('') #or other type

    def __init__(self, **kwargs):
        super(TreeViewButton, self).__init__(**kwargs)
        self.bind(is_selected = self.clk)

    def clk(self):
        #prints only on the selection and not on the deselection
        if self.is_selected:
            print(id)

class OrgChart(Screen, TreeViewButton):
...
    def createTree(self):
        tv = TreeView()
        for dict in self.extractNames():
            for key, value in dict.items():
                if key == "Button_ID":
                    self.ids.tv.add_node(TreeViewButton(id = value))
                    #self.id=value
                    #self.bind(on_press=self.clk)

干杯。在

相关问题 更多 >