我正在尝试循环add_nodes
到TreeView
。
我有一个包含雇用信息和分配 ID 的 sql 数据库。我需要从数据库中添加具有名称的节点,并从数据库中分配变量 idTreeViewButton
它们各自的 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 文件:
#:import RiseInTransition kivy.uix.screenmanager.RiseInTransition
#:import ListAdapter kivy.adapters.listadapter.ListAdapter
#:import ListAdapter kivy.adapters.listadapter.ListAdapter
#:import ListItemButton kivy.uix.listview.ListItemButton
#:import Factory kivy.factory.Factory
#:import TreeViewLabel kivy.uix.treeview.TreeViewLabel
#:import TreeViewNode kivy.uix.treeview.TreeViewNode
#:import Image kivy.uix.image
<OrgChart>:
name: "OrgChart"
ScrollView:
GridLayout:
cols: 3
size_hint_y: None
height: self.minimum_height
do_scroll_x: False
TreeView:
id: tv
root_options: {'text': 'Root directory','font_size': 15}
size_hint_y: None
height: self.minimum_height
Widget:
size_hint: [.8,.12]
Widget:
size_hint: [.8,.12]
试试这个:
...
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)
干杯。