import json
import os
import tkinter as tk
from tkinter import messagebox, simpledialog, ttk
from uuid import uuid4
APP_DIR = os.path.join(os.getenv("APPDATA") or os.path.expanduser("~"), "TreeList")
DATA_FILE = os.path.join(APP_DIR, "list.json")
def load_items():
try:
with open(DATA_FILE, "r", encoding="utf-8") as file:
return json.load(file)
except (OSError, json.JSONDecodeError):
return
def save_items():
os.makedirs(APP_DIR, exist_ok=True)
with open(DATA_FILE, "w", encoding="utf-8") as file:
json.dump(items, file, ensure_ascii=False, indent=2)
def ask_name(title, initial=""):
name = simpledialog.askstring(title, "Название (не больше пяти слов):", initialvalue=initial)
if name is None:
return None
name = name.strip()
if not name:
messagebox.showwarning("Пустое название", "Введите название пункта.")
return None
if len(name.split()) > 5:
messagebox.showwarning("Слишком длинное название", "Название должно содержать не больше пяти слов.")
return None
return name
def find_item(nodes, item_id):
for item in nodes:
if item["id"] == item_id:
return item
found = find_item(item.get("children", ), item_id)
if found:
return found
return None
def find_parent(nodes, item_id):
for item in nodes:
if any(child["id"] == item_id for child in item.get("children", )):
return item
found = find_parent(item.get("children", ), item_id)
if found:
return found
return None
def add_nodes(nodes, parent=""):
for item in nodes:
tree.insert(parent, "end", iid=item["id"], text=item["name"], open=True)
add_nodes(item.get("children", ), item["id"])
add_nodes(items)
def add_root():
name = ask_name("Новый пункт")
if name:
items.append({"id": str(uuid4()), "name": name, "children": })
save_items()
draw_tree()
def add_child():
selection = tree.selection()
if not selection:
messagebox.showinfo("Выберите пункт", "Сначала выберите пункт, к которому добавить подпункт.")
return