实现效果:
图标在此

替换前:

吐槽:这原版看着也不像原版😃
替换后:

 
代码:
注:必须要.ico图标文件
import winreg
import ctypes
import sys
import os
# 使用管理员身份打开程序
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
def set_exe_icon():
    try:
        # 获取当前 Python 脚本的路径
        current_path = os.path.abspath(sys.argv[0])
        # 从路径中提取目录部分
        current_dir = os.path.dirname(current_path)
        # 构建图标文件的路径,假设图标文件在当前目录下的 mp4/favicon.ico
        sys_icon_path = os.path.join(current_dir, 'mp4/favicon.ico')
        # 打开相关的注册表项
        key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, '.exe', 0, winreg.KEY_SET_VALUE)
        winreg.SetValue(key, '', winreg.REG_SZ, 'exefile')
        key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, 'exefile\\DefaultIcon', 0, winreg.KEY_SET_VALUE)
        winreg.SetValue(key, '', winreg.REG_SZ, sys_icon_path)
        print("修改默认图标成功!")
    except Exception as e:
        print(f"修改默认图标失败:{str(e)}")
set_exe_icon()
 
代码解析:
以下是对这段程序的作用和原理的详细解析:
作用:
 这段程序的主要作用是尝试修改 Windows 系统中 .exe 文件的默认图标。
原理:
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1):这行代码使用ctypes库以管理员身份运行当前的 Python 程序。这样做是因为修改注册表通常需要管理员权限。def set_exe_icon()函数:这是定义的主要执行功能的函数。current_path = os.path.abspath(sys.argv[0]):获取当前运行的 Python 脚本的绝对路径。current_dir = os.path.dirname(current_path):从绝对路径中提取出目录部分。sys_icon_path = os.path.join(current_dir, 'mp4/favicon.ico'):构建图标文件的完整路径,假设图标文件位于当前目录下的mp4文件夹中,文件名为favicon.ico。- 接下来,通过 
winreg.OpenKey打开注册表中的相关项:- 首先打开 
.exe对应的注册表项,并设置其值为exefile。 - 然后打开 
exefile\\DefaultIcon注册表项,并将构建好的图标路径设置为其值。 
 - 首先打开 
 - 如果整个过程没有出现异常,就打印出“修改默认图标成功!”;如果出现异常,则打印出相应的错误信息。
 


















