分组只有根节点能渲染到界面上,子节点无法渲染到界面
界面代码
# 创建分组列表
self.group_tree = ttk.Treeview(self.left_frame,show='tree')
self.group_tree.pack(side = tk.LEFT,fill=tk.Y, expand=True) # 填充 纵向 边距10
新建分组
def add_folder(self,name,local):
try:
if local == '根节点':
self.log.write_log_info(local + '等于根节点,分组添加到根节点')
parent_id = None
else:
selected_item = self.group_tree.focus()
selected_item_name = self.group_tree.item(selected_item)['text']
selected_item_id = self.db.get_group_id(selected_item_name)
self.log.write_log_info('添加到当前节点下 : ' + selected_item_name + ' ' + str(selected_item_id))
parent_id = selected_item_id
if name == '':
messagebox.showerror('错误', '分组名称不能为空!')
return
# 查询分组是否已存在
flag = self.db.exists(name, "groups")
if flag:
messagebox.showerror('错误', '分组已存在!')
return
# 将新节点ID存储到数据库
self.db.add_group(name, parent_id)
# 刷新分组列表
self.group_tree.delete(*self.group_tree.get_children())
self.init_groups_data()
self.log.write_log_info('分组添加成功')
except Exception as e:
messagebox.showerror('错误', f'添加分组失败: {str(e)}')
self.log.write_log_error(f'添加分组失败: {str(e)}')
初始化分组
# 初始化组数据
def init_groups_data(self,tree,images):
try:
conn = sqlite3.connect(self.db)
cursor = conn.cursor()
cursor.execute("SELECT * FROM groups")
results = cursor.fetchall()
# 递归函数,用来渲染给定父节点下的所有子节点
def render_subnodes(parent_node, nodes_dict, images):
"""递归函数,用来渲染给定父节点下的所有子节点"""
if parent_node in nodes_dict:
print(f"Rendering subnodes for parent: {parent_node}")
for group_id, name in nodes_dict[parent_node]:
child_node = tree.insert(parent_node, 'end', text=name, open=True, image=images)
print(f"Inserted child node: {child_node} with name: {name}")
render_subnodes(child_node, nodes_dict, images) # 继续深入下一个层次
# 创建一个字典来存储每个节点的记录和其对应的所有子节点
nodes_dict = {}
for result in results:
group_id, name, parent_id = result[:3]
if parent_id not in nodes_dict:
nodes_dict[parent_id] = []
nodes_dict[parent_id].append((group_id, name))
# 打印 nodes_dict 以检查数据是否正确
print("Nodes Dict:", nodes_dict)
# 开始渲染树状结构
# 先处理顶级节点(parent_id 是 None 的)
for group_id, name in nodes_dict.get(None, []):
top_node = tree.insert('', 'end', text=name, open=True, image=images)
# 接着递归处理所有的子节点
render_subnodes(top_node, nodes_dict, images)
except Exception as e:
print(f"Error: {e}")
finally:
cursor.close()
conn.close()