主要使用豆包里面的deepseek来生成。
指令:能不能用python3写一个代码,实现功能,有一个可视化界面,可以去绑定不同文件夹的路径,实现桌面快捷方式的一个功能

[color=]成品链接:https://www.123865.com/s/TKR5Vv-hyl5v
鄙人贴心的为大家准备了四种丑陋的主题颜色,放心,个顶个的丑。
1.浅色

2.深色

3.蓝色

4.绿色

源代码如下,愿有志之士能够好好优化一番,不胜感激。
[Python] 纯文本查看 复制代码import os
import shutil
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, Menu
import json
import platform
import ctypes
from PIL import Image, ImageTk
import threading
import time
import subprocess
class ThemeManager:
"""管理不同的UI主题"""
THEMES = {
"dark": {
"name": "深色主题",
"BACKGROUND": "#1E1E1E",
"FOREGROUND": "#FFFFFF",
"PRIMARY": "#165DFF",
"SECONDARY": "#303030",
"TERTIARY": "#404040",
"HIGHLIGHT": "#2A85FF",
"ERROR": "#FF5252",
"SUCCESS": "#4CAF50",
"TITLE_FONT": ("Segoe UI", 14, "bold"),
"HEADING_FONT": ("Segoe UI", 12, "bold"),
"NORMAL_FONT": ("Segoe UI", 10),
"SMALL_FONT": ("Segoe UI", 9)
},
"light": {
"name": "浅色主题",
"BACKGROUND": "#F5F5F5",
"FOREGROUND": "#000000",
"PRIMARY": "#1976D2",
"SECONDARY": "#E0E0E0",
"TERTIARY": "#BDBDBD",
"HIGHLIGHT": "#42A5F5",
"ERROR": "#D32F2F",
"SUCCESS": "#388E3C",
"TITLE_FONT": ("Segoe UI", 14, "bold"),
"HEADING_FONT": ("Segoe UI", 12, "bold"),
"NORMAL_FONT": ("Segoe UI", 10),
"SMALL_FONT": ("Segoe UI", 9)
},
"blue": {
"name": "蓝色主题",
"BACKGROUND": "#0A2463",
"FOREGROUND": "#FFFFFF",
"PRIMARY": "#3E92CC",
"SECONDARY": "#124E78",
"TERTIARY": "#5D737E",
"HIGHLIGHT": "#84D2F6",
"ERROR": "#FF6B6B",
"SUCCESS": "#6BCB77",
"TITLE_FONT": ("Segoe UI", 14, "bold"),
"HEADING_FONT": ("Segoe UI", 12, "bold"),
"NORMAL_FONT": ("Segoe UI", 10),
"SMALL_FONT": ("Segoe UI", 9)
},
"green": {
"name": "绿色主题",
"BACKGROUND": "#004B23",
"FOREGROUND": "#FFFFFF",
"PRIMARY": "#008000",
"SECONDARY": "#2B9348",
"TERTIARY": "#55A630",
"HIGHLIGHT": "#80B918",
"ERROR": "#D90429",
"SUCCESS": "#70E000",
"TITLE_FONT": ("Segoe UI", 14, "bold"),
"HEADING_FONT": ("Segoe UI", 12, "bold"),
"NORMAL_FONT": ("Segoe UI", 10),
"SMALL_FONT": ("Segoe UI", 9)
}
}
@staticmethod
def get_theme(theme_name):
"""获取指定主题的配置"""
return ThemeManager.THEMES.get(theme_name, ThemeManager.THEMES["dark"])
@staticmethod
def get_theme_names():
"""获取所有主题的名称"""
return [theme["name"] for theme in ThemeManager.THEMES.values()]
@staticmethod
def get_theme_keys():
"""获取所有主题的键"""
return list(ThemeManager.THEMES.keys())
class DesktopShortcutManager:
def __init__(self, root):
self.root = root
self.root.title("桌面快捷方式管理器")
self.root.geometry("800x550") # 增加窗口大小
self.root.resizable(True, True)
# 默认主题
self.current_theme = "dark"
# 尝试从配置文件加载上次使用的主题
self.config_file = "shortcut_manager_config.json"
self.load_config()
# 设置窗口图标和任务栏图标
self.setup_window_icon()
# 创建状态栏
self.create_status_bar()
# 设置自定义样式
self.style = ttk.Style()
self.setup_styles()
# 设置窗口背景
self.root.configure(bg=self.get_current_theme()["BACKGROUND"])
# 数据存储
self.shortcuts = {}
self.shortcuts_file = "desktop_shortcuts.json"
# 图标缓存
self.icon_cache = {}
self.default_icon = None
# 加载已保存的快捷方式
self.load_shortcuts()
# 创建菜单
self.create_menu()
# 创建界面
self.create_widgets()
# 显示欢迎消息
self.show_status_message("欢迎使用桌面快捷方式管理器")
def get_current_theme(self):
"""获取当前主题配置"""
return ThemeManager.get_theme(self.current_theme)
def load_config(self):
"""加载配置文件"""
if os.path.exists(self.config_file):
try:
with open(self.config_file, 'r', encoding='utf-8') as f:
config = json.load(f)
if "theme" in config and config["theme"] in ThemeManager.get_theme_keys():
self.current_theme = config["theme"]
except Exception as e:
self.show_status_message(f"加载配置失败: {str(e)}", "error")
def save_config(self):
"""保存配置文件"""
try:
with open(self.config_file, 'w', encoding='utf-8') as f:
json.dump({"theme": self.current_theme}, f)
except Exception as e:
self.show_status_message(f"保存配置失败: {str(e)}", "error")
def setup_window_icon(self):
"""设置窗口图标和任务栏图标"""
try:
if platform.system() == 'Windows':
# 设置任务栏图标
myappid = 'desktop.shortcut.manager.1.0'
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
# 尝试设置窗口图标
if os.path.exists("icon.ico"):
self.root.iconbitmap("icon.ico")
except:
pass
def setup_styles(self):
"""设置自定义UI样式"""
theme = self.get_current_theme()
# 主题设置
self.style.theme_use("clam")
# 背景颜色
self.style.configure(".", background=theme["BACKGROUND"],
foreground=theme["FOREGROUND"],
font=theme["NORMAL_FONT"])
# 框架样式
self.style.configure("TFrame", background=theme["BACKGROUND"])
self.style.configure("TLabelframe", background=theme["BACKGROUND"],
foreground=theme["FOREGROUND"],
font=theme["HEADING_FONT"])
self.style.configure("TLabelframe.Label", background=theme["BACKGROUND"],
foreground=theme["FOREGROUND"],
font=theme["HEADING_FONT"])
# 按钮样式
self.style.configure("TButton", background=theme["SECONDARY"],
foreground=theme["FOREGROUND"],
borderwidth=0,
padding=8)
self.style.map("TButton",
background=[("active", theme["PRIMARY"]),
("pressed", theme["HIGHLIGHT"])],
foreground=[("active", theme["FOREGROUND"]),
("pressed", theme["FOREGROUND"])])
# 列表框样式
self.style.configure("TListbox", background=theme["SECONDARY"],
foreground=theme["FOREGROUND"],
borderwidth=0,
relief="flat",
selectbackground=theme["PRIMARY"],
selectforeground=theme["FOREGROUND"])
# 滚动条样式
self.style.configure("Vertical.TScrollbar", background=theme["TERTIARY"],
troughcolor=theme["SECONDARY"],
arrowcolor=theme["FOREGROUND"])
self.style.map("Vertical.TScrollbar",
background=[("active", theme["PRIMARY"])])
# 菜单样式
self.style.configure("TMenubutton", background=theme["SECONDARY"],
foreground=theme["FOREGROUND"],
borderwidth=0)
self.style.map("TMenubutton",
background=[("active", theme["PRIMARY"]),
("pressed", theme["HIGHLIGHT"])])
# 树形视图样式
self.style.configure("Treeview",
background=theme["SECONDARY"],
foreground=theme["FOREGROUND"],
rowheight=30, # 增加行高
fieldbackground=theme["SECONDARY"],
borderwidth=0)
self.style.configure("Treeview.Heading",
background=theme["TERTIARY"],
foreground=theme["FOREGROUND"],
font=theme["HEADING_FONT"])
self.style.map("Treeview",
background=[("selected", theme["PRIMARY"]),
("active", theme["HIGHLIGHT"])])
def change_theme(self, theme_key):
"""更改UI主题"""
if theme_key not in ThemeManager.get_theme_keys():
return
self.current_theme = theme_key
self.setup_styles()
# 重新配置所有需要更新的UI元素
self.root.configure(bg=self.get_current_theme()["BACKGROUND"])
self.title_label.configure(foreground=self.get_current_theme()["PRIMARY"])
# 更新树形视图样式
self.update_treeview_style()
# 更新确认对话框的背景
self.update_dialog_bg()
# 保存当前主题设置
self.save_config()
# 显示主题更改成功消息
theme_name = ThemeManager.get_theme(theme_key)["name"]
self.show_status_message(f"已切换到 {theme_name}", "success")
def update_treeview_style(self):
"""更新树形视图的样式"""
theme = self.get_current_theme()
# 重新配置树形视图
self.style.configure("Treeview",
background=theme["SECONDARY"],
foreground=theme["FOREGROUND"],
fieldbackground=theme["SECONDARY"])
self.style.map("Treeview",
background=[("selected", theme["PRIMARY"]),
("active", theme["HIGHLIGHT"])])
# 刷新树形视图内容
self.refresh_shortcut_list()
def update_dialog_bg(self):
"""更新所有打开的对话框的背景颜色"""
theme = self.get_current_theme()
# 查找所有对话框窗口并更新其背景
for child in self.root.winfo_children():
if isinstance(child, tk.Toplevel):
child.configure(bg=theme["BACKGROUND"])
for widget in child.winfo_children():
if isinstance(widget, ttk.Label):
widget.configure(background=theme["BACKGROUND"],
foreground=theme["FOREGROUND"])
elif isinstance(widget, ttk.Frame):
widget.configure(style="TFrame")
elif isinstance(widget, ttk.Button):
widget.configure(style="TButton")
def create_menu(self):
"""创建菜单栏"""
menubar = Menu(self.root)
# 文件菜单
file_menu = Menu(menubar, tearoff=0)
file_menu.add_command(label="保存所有快捷方式", command=self.save_shortcuts)
file_menu.add_separator()
file_menu.add_command(label="退出", command=self.root.quit)
menubar.add_cascade(label="文件", menu=file_menu)
# 主题菜单
theme_menu = Menu(menubar, tearoff=0)
for theme_key in ThemeManager.get_theme_keys():
theme_name = ThemeManager.get_theme(theme_key)["name"]
theme_menu.add_command(label=theme_name,
command=lambda key=theme_key: self.change_theme(key))
menubar.add_cascade(label="主题", menu=theme_menu)
# 帮助菜单
help_menu = Menu(menubar, tearoff=0)
help_menu.add_command(label="关于", command=self.show_about)
menubar.add_cascade(label="帮助", menu=help_menu)
# 设置菜单栏
self.root.config(menu=menubar)
def show_about(self):
"""显示关于对话框"""
about_window = tk.Toplevel(self.root)
about_window.title("关于")
about_window.geometry("300x200")
about_window.configure(bg=self.get_current_theme()["BACKGROUND"])
about_window.transient(self.root)
about_window.grab_set()
# 居中显示
self.root.update_idletasks()
x = self.root.winfo_x() + (self.root.winfo_width() - 300) // 2
y = self.root.winfo_y() + (self.root.winfo_height() - 200) // 2
about_window.geometry(f"+{x}+{y}")
# 图标
icon_label = ttk.Label(about_window, text="📁",
font=("Arial", 36),
foreground=self.get_current_theme()["PRIMARY"],
background=self.get_current_theme()["BACKGROUND"])
icon_label.pack(pady=(15, 5))
# 标题
title_label = ttk.Label(about_window,
text="桌面快捷方式管理器",
font=self.get_current_theme()["TITLE_FONT"],
background=self.get_current_theme()["BACKGROUND"],
foreground=self.get_current_theme()["FOREGROUND"])
title_label.pack(pady=(0, 5))
# 版本
version_label = ttk.Label(about_window,
text="版本 1.2",
font=self.get_current_theme()["NORMAL_FONT"],
background=self.get_current_theme()["BACKGROUND"],
foreground=self.get_current_theme()["FOREGROUND"])
version_label.pack(pady=(0, 15))
# 确定按钮
ok_btn = ttk.Button(about_window, text="确定",
command=about_window.destroy,
style="TButton")
ok_btn.pack(pady=(0, 15))
# 设置焦点
ok_btn.focus_set()
def create_widgets(self):
"""创建美化后的界面组件"""
# 创建主框架
main_frame = ttk.Frame(self.root, padding="15")
main_frame.pack(fill=tk.BOTH, expand=True)
# 标题
self.title_label = ttk.Label(main_frame, text="桌面快捷方式管理器",
font=self.get_current_theme()["TITLE_FONT"],
foreground=self.get_current_theme()["PRIMARY"])
self.title_label.pack(anchor="w", pady=(0, 15))
# 分割线
separator = ttk.Separator(main_frame, orient="horizontal")
separator.pack(fill=tk.X, pady=(0, 15))
# 创建内容框架
content_frame = ttk.Frame(main_frame)
content_frame.pack(fill=tk.BOTH, expand=True)
# 左侧列表框架
list_frame = ttk.LabelFrame(content_frame, text="快捷方式列表", padding="10")
list_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0, 10))
# 创建树形视图替代列表框
self.setup_treeview(list_frame)
# 右侧操作框架
action_frame = ttk.Frame(content_frame)
action_frame.pack(side=tk.RIGHT, fill=tk.Y)
# 添加快捷方式按钮
add_btn = ttk.Button(action_frame, text="添加快捷方式",
command=self.add_shortcut,
style="TButton")
add_btn.pack(fill=tk.X, padx=5, pady=(0, 10))
# 打开快捷方式按钮
open_btn = ttk.Button(action_frame, text="打开快捷方式",
command=self.open_selected_shortcut,
style="TButton")
open_btn.pack(fill=tk.X, padx=5, pady=(0, 10))
# 删除快捷方式按钮
delete_btn = ttk.Button(action_frame, text="删除快捷方式",
command=self.delete_shortcut,
style="TButton")
delete_btn.pack(fill=tk.X, padx=5, pady=(0, 10))
# 创建快捷方式到桌面按钮
create_btn = ttk.Button(action_frame, text="创建到桌面",
command=self.create_desktop_shortcut,
style="TButton")
create_btn.pack(fill=tk.X, padx=5, pady=(0, 10))
# 刷新列表
self.refresh_shortcut_list()
def setup_treeview(self, parent):
"""设置树形视图"""
# 创建树形视图
columns = ("name", "path")
self.shortcut_tree = ttk.Treeview(parent, columns=columns, show="headings")
# 设置列标题
self.shortcut_tree.heading("name", text="名称")
self.shortcut_tree.heading("path", text="路径")
# 设置列宽
self.shortcut_tree.column("name", width=150, anchor="w")
self.shortcut_tree.column("path", width=300, anchor="w")
# 添加滚动条
scrollbar = ttk.Scrollbar(parent, orient="vertical", command=self.shortcut_tree.yview)
self.shortcut_tree.configure(yscrollcommand=scrollbar.set)
# 布局
self.shortcut_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# 绑定双击事件
self.shortcut_tree.bind("", self.on_tree_double_click)
# 绑定选择事件
self.shortcut_tree.bind("", self.on_tree_select)
# 绑定右键菜单
self.shortcut_tree.bind("[B]", self.on_tree_right_click)
# 创建右键菜单
self.create_context_menu()
def create_context_menu(self):
"""创建右键菜单"""
self.context_menu = Menu(self.root, tearoff=0)
self.context_menu.add_command(label="打开", command=self.open_selected_shortcut)
self.context_menu.add_separator()
self.context_menu.add_command(label="删除", command=self.delete_shortcut)
self.context_menu.add_separator()
self.context_menu.add_command(label="创建到桌面", command=self.create_desktop_shortcut)
def on_tree_right_click(self, event):
"""树形视图右键点击事件"""
# 获取点击的项
item = self.shortcut_tree.identify_row(event.y)
if item:
# 选择点击的项
self.shortcut_tree.selection_set(item)
# 显示右键菜单
self.context_menu.post(event.x_root, event.y_root)
def on_tree_double_click(self, event):
"""树形视图双击事件"""
self.open_selected_shortcut()
def on_tree_select(self, event):
"""树形视图选择事件"""
selected_items = self.shortcut_tree.selection()
if selected_items:
item = selected_items[0]
folder_path = self.shortcut_tree.item(item, "values")[1]
self.show_status_message(f"已选择: {folder_path}", "info", -1)
def get_selected_shortcut(self):
"""获取选中的快捷方式名称"""
selected_items = self.shortcut_tree.selection()
if not selected_items:
return None
return self.shortcut_tree.item(selected_items[0], "values")[0]
def get_selected_shortcut_path(self):
"""获取选中的快捷方式路径"""
selected_items = self.shortcut_tree.selection()
if not selected_items:
return None
return self.shortcut_tree.item(selected_items[0], "values")[1]
def create_status_bar(self):
"""创建状态栏"""
self.status_bar = ttk.Frame(self.root, relief="sunken", padding=5)
self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
self.status_message = ttk.Label(self.status_bar, text="",
anchor="w",
font=self.get_current_theme()["SMALL_FONT"])
self.status_message.pack(side=tk.LEFT, fill=tk.X, expand=True)
self.status_icon = ttk.Label(self.status_bar, text="")
self.status_icon.pack(side=tk.RIGHT, padx=(0, 10))
def show_status_message(self, message, icon="info", duration=3000):
"""显示状态栏消息"""
self.status_message.config(text=message)
# 设置图标
if icon == "info":
self.status_icon.config(text="ℹ️")
self.status_icon.config(foreground=self.get_current_theme()["PRIMARY"])
elif icon == "success":
self.status_icon.config(text="✅")
self.status_icon.config(foreground=self.get_current_theme()["SUCCESS"])
elif icon == "error":
self.status_icon.config(text="❌")
self.status_icon.config(foreground=self.get_current_theme()["ERROR"])
# 如果设置了持续时间,定时清除消息
if duration > 0:
threading.Thread(target=self.clear_status_after_delay,
args=(duration,)).start()
def clear_status_after_delay(self, delay):
"""延迟后清除状态栏消息"""
time.sleep(delay / 1000)
if self.root.winfo_exists():
self.root.after(0, self.clear_status_message)
def clear_status_message(self):
"""清除状态栏消息"""
self.status_message.config(text="")
self.status_icon.config(text="")
def load_shortcuts(self):
"""从文件加载已保存的快捷方式"""
if os.path.exists(self.shortcuts_file):
try:
with open(self.shortcuts_file, 'r', encoding='utf-8') as f:
self.shortcuts = json.load(f)
self.show_status_message(f"已加载 {len(self.shortcuts)} 个快捷方式", "success")
except Exception as e:
self.show_status_message(f"加载快捷方式失败: {str(e)}", "error")
self.shortcuts = {}
else:
self.shortcuts = {}
def save_shortcuts(self):
"""保存快捷方式到文件"""
try:
with open(self.shortcuts_file, 'w', encoding='utf-8') as f:
json.dump(self.shortcuts, f, ensure_ascii=False, indent=4)
return True
except Exception as e:
self.show_status_message(f"保存快捷方式失败: {str(e)}", "error")
return False
def refresh_shortcut_list(self):
"""刷新快捷方式列表"""
# 清空树形视图
for item in self.shortcut_tree.get_children():
self.shortcut_tree.delete(item)
# 重新添加所有快捷方式
for name, path in self.shortcuts.items():
# 尝试获取文件夹图标
icon = self.get_folder_icon(path)
self.shortcut_tree.insert("", tk.END, values=(name, path), image=icon)
def get_folder_icon(self, folder_path):
"""获取文件夹图标"""
# 检查缓存
if folder_path in self.icon_cache:
return self.icon_cache[folder_path]
# 为了简化,我们使用默认图标
# 实际应用中,您可以尝试获取系统文件夹图标
# 这里我们使用一个简单的文件夹图标
if self.default_icon is None:
# 创建一个简单的文件夹图标
try:
# 创建一个16x16的文件夹图标
folder_icon = Image.new('RGBA', (16, 16), (0, 0, 0, 0))
# 绘制文件夹
folder_color = self.get_current_theme()["PRIMARY"]
if isinstance(folder_color, str) and folder_color.startswith("#"):
# 转换十六进制颜色为RGB
r = int(folder_color[1:3], 16)
g = int(folder_color[3:5], 16)
b = int(folder_color[5:7], 16)
folder_color = (r, g, b, 255)
# 绘制文件夹主体
folder_icon.paste(folder_color, (0, 4, 16, 16))
# 绘制文件夹顶部
folder_icon.paste(folder_color, (0, 0, 8, 4))
# 转换为Tkinter可用的图像
self.default_icon = ImageTk.PhotoImage(folder_icon)
except:
# 如果出错,使用None作为图标
self.default_icon = None
# 缓存图标
self.icon_cache[folder_path] = self.default_icon
return self.default_icon
def add_shortcut(self):
"""添加新的快捷方式"""
folder_path = filedialog.askdirectory(title="选择文件夹")
if not folder_path:
return
# 获取文件夹名称作为快捷方式名称
folder_name = os.path.basename(folder_path)
# 如果已存在同名快捷方式,添加数字后缀
base_name = folder_name
counter = 1
while folder_name in self.shortcuts:
folder_name = f"{base_name} ({counter})"
counter += 1
# 添加到快捷方式字典
self.shortcuts[folder_name] = folder_path
# 保存并刷新列表
if self.save_shortcuts():
self.refresh_shortcut_list()
self.show_status_message(f"已添加快捷方式: {folder_name}", "success")
# 自动选择新添加的快捷方式
for item in self.shortcut_tree.get_children():
if self.shortcut_tree.item(item, "values")[0] == folder_name:
self.shortcut_tree.selection_set(item)
self.shortcut_tree.see(item)
break
def open_selected_shortcut(self):
"""打开选中的快捷方式"""
shortcut_name = self.get_selected_shortcut()
if not shortcut_name:
return
folder_path = self.shortcuts[shortcut_name]
self.show_status_message(f"正在打开: {folder_path}", "info")
self.open_folder(folder_path)
def open_folder(self, folder_path):
"""打开指定文件夹"""
if not os.path.exists(folder_path):
self.show_status_message(f"文件夹不存在: {folder_path}", "error")
return
try:
if platform.system() == 'Windows':
os.startfile(folder_path)
elif platform.system() == 'Darwin': # macOS
os.system(f'open "{folder_path}"')
else: # Linux
os.system(f'xdg-open "{folder_path}"')
self.show_status_message(f"已打开: {folder_path}", "success")
except Exception as e:
self.show_status_message(f"无法打开文件夹: {str(e)}", "error")
def delete_shortcut(self):
"""删除选中的快捷方式"""
shortcut_name = self.get_selected_shortcut()
if not shortcut_name:
return
# 创建自定义确认对话框 - 增加高度并优化布局
confirm_window = tk.Toplevel(self.root)
confirm_window.title("确认删除")
confirm_window.geometry("400x180") # 增加高度
confirm_window.configure(bg=self.get_current_theme()["BACKGROUND"])
confirm_window.transient(self.root)
confirm_window.grab_set()
# 居中显示
self.root.update_idletasks()
x = self.root.winfo_x() + (self.root.winfo_width() - 400) // 2
y = self.root.winfo_y() + (self.root.winfo_height() - 180) // 2
confirm_window.geometry(f"+{x}+{y}")
# 主内容框架 - 增加内边距
content_frame = ttk.Frame(confirm_window, padding=15)
content_frame.pack(fill=tk.BOTH, expand=True)
# 警告图标和消息
icon_label = ttk.Label(content_frame, text="⚠️",
font=("Arial", 24),
foreground=self.get_current_theme()["ERROR"],
background=self.get_current_theme()["BACKGROUND"])
icon_label.grid(row=0, column=0, rowspan=2, padx=(0, 10))
message_label = ttk.Label(content_frame,
text=f"确定要删除快捷方式 '{shortcut_name}' 吗?",
background=self.get_current_theme()["BACKGROUND"],
foreground=self.get_current_theme()["FOREGROUND"],
font=self.get_current_theme()["NORMAL_FONT"],
wraplength=300) # 允许文本换行
message_label.grid(row=0, column=1, sticky="w")
# 按钮框架 - 使用grid布局并增加间距
button_frame = ttk.Frame(content_frame, padding=(0, 20, 0, 0))
button_frame.grid(row=1, column=0, columnspan=2, sticky="ew")
# 添加弹性空间使按钮居中
button_frame.columnconfigure(0, weight=1)
button_frame.columnconfigure(1, weight=1)
button_frame.columnconfigure(2, weight=1)
button_frame.columnconfigure(3, weight=1)
# 取消按钮
cancel_btn = ttk.Button(button_frame, text="取消",
command=confirm_window.destroy,
width=10,
style="TButton")
cancel_btn.grid(row=0, column=1, padx=5)
# 确认删除按钮
def on_confirm():
del self.shortcuts[shortcut_name]
if self.save_shortcuts():
self.refresh_shortcut_list()
self.show_status_message(f"已删除快捷方式: {shortcut_name}", "success")
confirm_window.destroy()
delete_btn = ttk.Button(button_frame, text="删除",
command=on_confirm,
width=10,
style="TButton")
delete_btn.grid(row=0, column=2, padx=5)
# 设置焦点
cancel_btn.focus_set()
def create_desktop_shortcut(self):
"""创建选中的快捷方式到桌面"""
shortcut_name = self.get_selected_shortcut()
if not shortcut_name:
return
folder_path = self.shortcuts[shortcut_name]
if not os.path.exists(folder_path):
self.show_status_message(f"文件夹不存在: {folder_path}", "error")
return
self.show_status_message(f"正在创建桌面快捷方式: {shortcut_name}", "info")
# 获取桌面路径
if platform.system() == 'Windows':
desktop_path = os.path.join(os.path.expanduser('~'), 'Desktop')
shortcut_path = os.path.join(desktop_path, f"{shortcut_name}.lnk")
try:
# 使用VBScript创建Windows快捷方式
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut(shortcut_path)
shortcut.Targetpath = folder_path
shortcut.save()
self.show_status_message(f"已在桌面创建快捷方式: {shortcut_name}", "success")
except ImportError:
self.show_status_message("缺少win32com库,请安装pywin32: pip install pywin32", "error")
except Exception as e:
self.show_status_message(f"创建快捷方式失败: {str(e)}", "error")
else:
# Linux/macOS创建符号链接
desktop_path = os.path.join(os.path.expanduser('~'), 'Desktop')
shortcut_path = os.path.join(desktop_path, shortcut_name)
try:
# 检查是否已存在
if os.path.exists(shortcut_path) or os.path.islink(shortcut_path):
# 创建自定义确认对话框
confirm_window = tk.Toplevel(self.root)
confirm_window.title("确认覆盖")
confirm_window.geometry("350x150")
confirm_window.configure(bg=self.get_current_theme()["BACKGROUND"])
confirm_window.transient(self.root)
confirm_window.grab_set()
# 居中显示
self.root.update_idletasks()
x = self.root.winfo_x() + (self.root.winfo_width() - 350) // 2
y = self.root.winfo_y() + (self.root.winfo_height() - 150) // 2
confirm_window.geometry(f"+{x}+{y}")
# 对话框内容
icon_label = ttk.Label(confirm_window, text="⚠️",
font=("Arial", 24),
foreground=self.get_current_theme()["ERROR"],
background=self.get_current_theme()["BACKGROUND"])
icon_label.pack(pady=(15, 5))
message_label = ttk.Label(confirm_window,
text=f"桌面已存在名为 '{shortcut_name}' 的文件,是否覆盖?",
background=self.get_current_theme()["BACKGROUND"],
foreground=self.get_current_theme()["FOREGROUND"],
font=self.get_current_theme()["NORMAL_FONT"])
message_label.pack(pady=(0, 15))
# 按钮框架
button_frame = ttk.Frame(confirm_window, background=self.get_current_theme()["BACKGROUND"])
button_frame.pack(fill=tk.X, padx=20)
# 取消按钮
cancel_btn = ttk.Button(button_frame, text="取消",
command=confirm_window.destroy,
style="TButton")
cancel_btn.pack(side=tk.RIGHT, padx=(5, 0))
# 确认覆盖按钮
def on_confirm_override():
if os.path.islink(shortcut_path):
os.unlink(shortcut_path)
else:
os.remove(shortcut_path)
# 创建符号链接
os.symlink(folder_path, shortcut_path)
self.show_status_message(f"已在桌面创建快捷方式: {shortcut_name}", "success")
confirm_window.destroy()
override_btn = ttk.Button(button_frame, text="覆盖",
command=on_confirm_override,
style="TButton")
override_btn.pack(side=tk.RIGHT)
# 设置焦点
cancel_btn.focus_set()
else:
# 创建符号链接
os.symlink(folder_path, shortcut_path)
self.show_status_message(f"已在桌面创建快捷方式: {shortcut_name}", "success")
except Exception as e:
self.show_status_message(f"创建快捷方式失败: {str(e)}", "error")
if __name__ == "__main__":
root = tk.Tk()
app = DesktopShortcutManager(root)
root.mainloop()