我试图将add_nodes
循环到TreeView
。
我有一个SQL数据库,其中包含用人信息和一个分配的ID。我需要从数据库添加其名称的节点,并从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文件:
#: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]
答案 0 :(得分:0)
尝试一下:
...
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)
干杯。