This commit is contained in:
仙君御 2024-11-19 19:03:12 +08:00
parent 438523c0ea
commit 39be40f81c
3 changed files with 59 additions and 48 deletions

11
README.md Normal file
View File

@ -0,0 +1,11 @@
# 目录图标工具 FilesTreeIco_Tool
在Windows上编辑配置来快速创建文件夹目录结构并设置图标
### ./图标
该路径下可放入自定义图片作为文件夹图标候选
### ./*.json
程序会依赖.json配置文件来记录目录结构和图标配置

View File

@ -1 +0,0 @@
pyinstaller -F main.py

95
main.py
View File

@ -8,11 +8,12 @@ from typing import Dict, Optional
from PIL import Image from PIL import Image
import subprocess import subprocess
import shutil import shutil
from PIL import ImageTk
class ConfigEditorGUI: class ConfigEditorGUI:
def __init__(self, root): def __init__(self, root):
self.root = root self.root = root
self.root.title("目录配置编辑器") self.root.title("目录图标工具 FilesTreeIco_Tool")
self.root.geometry("800x600") self.root.geometry("800x600")
# 设置基本样式 # 设置基本样式
@ -37,7 +38,7 @@ class ConfigEditorGUI:
self.main_frame = ttk.Frame(self.root, padding="10") self.main_frame = ttk.Frame(self.root, padding="10")
self.main_frame.pack(fill=tk.BOTH, expand=True) self.main_frame.pack(fill=tk.BOTH, expand=True)
# 顶部工具 # 顶部工具
self._create_toolbar() self._create_toolbar()
# 创建左右分栏 # 创建左右分栏
@ -104,7 +105,7 @@ class ConfigEditorGUI:
font=('微软雅黑', 10) font=('微软雅黑', 10)
).pack(anchor='w', pady=(0, 10)) ).pack(anchor='w', pady=(0, 10))
# 创图标显示区域 # 创图标显示区域
icon_frame = ttk.Frame(main_frame) icon_frame = ttk.Frame(main_frame)
icon_frame.pack(fill=tk.BOTH, expand=True) icon_frame.pack(fill=tk.BOTH, expand=True)
@ -156,48 +157,40 @@ class ConfigEditorGUI:
# 加载实际图标 # 加载实际图标
icon_count = 1 # 从1开始计数因为0被"无图标"占用 icon_count = 1 # 从1开始计数因为0被"无图标"占用
for file in os.listdir('icons'): for file in os.listdir('图标'):
if file.lower().endswith(('.ico', '.png')): if file.lower().endswith(('.ico', '.png')):
try: try:
icon_path = os.path.join('icons', file) icon_path = os.path.join('图标', file)
if file.lower().endswith('.png'): if file.lower().endswith('.png'):
# 创建预览图标64x64 # 动态调整图标大小以适配预览
preview_size = 64 max_size = 24
original_icon = tk.PhotoImage(file=icon_path) preview_size = 32
original_icon = Image.open(icon_path)
# original_icon.thumbnail((max_size, max_size), Image.LANCZOS)
original_icon = original_icon.resize((preview_size, preview_size), Image.LANCZOS)
preview_icon = ImageTk.PhotoImage(original_icon)
# 计算缩放比例 # 创建图标按钮框架
scale = min(preview_size / original_icon.height(), preview_size / original_icon.width()) btn_frame = ttk.Frame(grid_frame)
scaled_w = int(original_icon.width() * scale) row = icon_count // 4 # 每行4个图标
scaled_h = int(original_icon.height() * scale) col = icon_count % 4
btn_frame.grid(row=row, column=col, padx=10, pady=10, sticky='nsew')
# 创建图标按钮
btn = ttk.Button(
btn_frame,
image=preview_icon,
command=lambda p=icon_path: on_icon_click(p)
)
btn.image = preview_icon # 保持引用
btn.pack(pady=2)
# 显示文件名(限制长度)
name = file if len(file) <= 15 else file[:12] + '...'
ttk.Label(btn_frame, text=name).pack()
icon_count += 1
if scaled_w > 0 and scaled_h > 0:
# 创建预览图标
preview_icon = original_icon.subsample(
max(1, original_icon.width() // scaled_w),
max(1, original_icon.height() // scaled_h)
)
# 创建图标按钮框架
btn_frame = ttk.Frame(grid_frame)
row = icon_count // 4 # 每行4个图标
col = icon_count % 4
btn_frame.grid(row=row, column=col, padx=10, pady=10, sticky='nsew')
# 创建图标按钮
btn = ttk.Button(
btn_frame,
image=preview_icon,
command=lambda p=icon_path: on_icon_click(p)
)
btn.image = preview_icon # 保持引用
btn.pack(pady=2)
# 显示文件名(限制长度)
name = file if len(file) <= 15 else file[:12] + '...'
ttk.Label(btn_frame, text=name).pack()
icon_count += 1
except Exception as e: except Exception as e:
print(f"无法加载图标 {file}: {str(e)}") print(f"无法加载图标 {file}: {str(e)}")
@ -241,7 +234,11 @@ class ConfigEditorGUI:
# 原有的图标设置逻辑 # 原有的图标设置逻辑
rel_path = os.path.relpath(icon_path) rel_path = os.path.relpath(icon_path)
if rel_path not in self.icon_cache: if rel_path not in self.icon_cache:
self.icon_cache[rel_path] = tk.PhotoImage(file=icon_path) original_icon = Image.open(icon_path)
# 动态调整图标大小以适配树状图
max_size = 16
original_icon.thumbnail((max_size, max_size), Image.LANCZOS)
self.icon_cache[rel_path] = ImageTk.PhotoImage(original_icon)
self.tree.item(item_id, image=self.icon_cache[rel_path]) self.tree.item(item_id, image=self.icon_cache[rel_path])
path = self._get_item_path(item_id) path = self._get_item_path(item_id)
@ -271,7 +268,7 @@ class ConfigEditorGUI:
return path return path
def _create_tree_editor(self): def _create_tree_editor(self):
"""创建右侧录树编辑器""" """创建右侧录树编辑器"""
editor_frame = ttk.LabelFrame(self.paned, text="目录结构", padding="5") editor_frame = ttk.LabelFrame(self.paned, text="目录结构", padding="5")
self.paned.add(editor_frame, weight=3) self.paned.add(editor_frame, weight=3)
@ -301,7 +298,7 @@ class ConfigEditorGUI:
self._load_config_file(filename) self._load_config_file(filename)
def _load_config_file(self, filename: str): def _load_config_file(self, filename: str):
"""加载指定配置文件""" """加载指定配置文件"""
try: try:
with open(filename, 'r', encoding='utf-8') as f: with open(filename, 'r', encoding='utf-8') as f:
self.folder_structure = json.load(f) self.folder_structure = json.load(f)
@ -327,7 +324,11 @@ class ConfigEditorGUI:
icon_path = content['_icon'] icon_path = content['_icon']
try: try:
if icon_path not in self.icon_cache: if icon_path not in self.icon_cache:
self.icon_cache[icon_path] = tk.PhotoImage(file=icon_path) original_icon = Image.open(icon_path)
# 动态调整图标大小以适配树状图
max_size = 16
original_icon.thumbnail((max_size, max_size), Image.LANCZOS)
self.icon_cache[icon_path] = ImageTk.PhotoImage(original_icon)
icon = self.icon_cache[icon_path] icon = self.icon_cache[icon_path]
except Exception as e: except Exception as e:
print(f"无法加载图标 {icon_path}: {str(e)}") print(f"无法加载图标 {icon_path}: {str(e)}")
@ -363,7 +364,7 @@ class ConfigEditorGUI:
self.tree.item(selected[0], open=True) self.tree.item(selected[0], open=True)
# 选中新节点 # 选中新节点
self.tree.selection_set(new_item) self.tree.selection_set(new_item)
# 确保新节点<EFBFBD><EFBFBD><EFBFBD> # 确保新节点
self.tree.see(new_item) self.tree.see(new_item)
# 立即保存更改 # 立即保存更改
self.folder_structure = {"folders": self._get_folder_structure('')} self.folder_structure = {"folders": self._get_folder_structure('')}
@ -521,7 +522,7 @@ def create_folders(base_path: str, folders: Dict, current_file) -> None:
subprocess.run(['attrib', '+s', '+h', desktop_ini_path], shell=True) subprocess.run(['attrib', '+s', '+h', desktop_ini_path], shell=True)
# 设置icon文件为隐藏文件 # 设置icon文件为隐藏文件
subprocess.run(['attrib', '+s', '+h', final_icon_path], shell=True) subprocess.run(['attrib', '+s', '+h', final_icon_path], shell=True)
# 设置文件夹为 # 设置文件夹为
subprocess.run(['attrib', '+r', folder_path], shell=True) subprocess.run(['attrib', '+r', folder_path], shell=True)
# 清除图标缓存 # 清除图标缓存
@ -550,7 +551,7 @@ def main():
root = tk.Tk() root = tk.Tk()
# 设置窗口图标 # 设置窗口图标
try: try:
root.iconbitmap("icons/app.ico") root.iconbitmap("图标/app.ico")
except: except:
pass pass