You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何通过exe文件路径获取对应应用的logo/图标

从EXE路径提取图标供Tkinter使用的实现

首先安装所需依赖库,用于调用Windows系统API提取图标、做格式转换适配Tkinter:
pip install pywin32 pillow


核心函数实现

import os
import win32api
import win32gui
import win32con
from PIL import Image, ImageTk

def get_image_from_path(file: str, icon_size: int = 32) -> ImageTk.PhotoImage:
    """
    传入exe文件路径,返回可直接在Tkinter中使用的图标对象
    :param file: exe文件的绝对路径
    :param icon_size: 返回图标的边长像素,默认32px
    """
    # 从exe中提取大图标句柄,参数1代表取大图标,0代表取小图标
    large_icons, _ = win32api.ExtractIconEx(file, 0, 1)
    if not large_icons:
        raise FileNotFoundError(f"无法从{file}中提取图标,请检查路径有效性")
    hicon = large_icons[0]
    
    # 创建设备上下文承载图标位图
    screen_dc = win32gui.GetDC(0)
    hdc = win32gui.CreateCompatibleDC(screen_dc)
    bmp = win32gui.CreateCompatibleBitmap(screen_dc, icon_size, icon_size)
    win32gui.SelectObject(hdc, bmp)
    
    # 将图标绘制到位图中
    win32gui.DrawIconEx(hdc, 0, 0, hicon, icon_size, icon_size, 0, None, win32con.DI_NORMAL)
    
    # 读取位图数据转换为PIL图像对象
    bmp_info = win32gui.GetObject(bmp)
    bmp_str = win32gui.GetBitmapBits(bmp, bmp_info.bmWidthBytes * bmp_info.bmHeight)
    img = Image.frombuffer(
        "RGBA",
        (bmp_info.bmWidth, bmp_info.bmHeight),
        bmp_str,
        "raw",
        "BGRA",
        bmp_info.bmWidthBytes,
        1
    )
    
    # 释放系统资源,避免内存泄漏
    win32gui.DeleteObject(bmp)
    win32gui.DeleteDC(hdc)
    win32gui.ReleaseDC(0, screen_dc)
    win32gui.DestroyIcon(hicon)
    
    # 转换为Tkinter可识别的图片对象返回
    return ImageTk.PhotoImage(img)

调用示例(对应Spotify启动场景)

import tkinter as tk

root = tk.Tk()
root.title("Spotify启动器")

spotify_path = r'C:\Users\John\AppData\Roaming\Spotify\Spotify.exe'
# 按你期望的形式调用获取图标
my_image = get_image_from_path(file=spotify_path)

# 界面上绑定图标和启动逻辑
launch_btn = tk.Button(root, image=my_image, command=lambda: os.startfile(spotify_path))
launch_btn.pack(padx=20, pady=20)

root.mainloop()

注意事项

  • 该方案仅支持Windows系统,EXE是Windows平台专属可执行格式,用到的图标提取接口也是Windows系统提供的原生API
  • 如果需要适配工具栏等场景的小尺寸图标,可以在调用时传入icon_size=16,也可以根据界面需求传入其他自定义尺寸
  • 返回的PhotoImage对象必须被全局变量或者类属性持有,否则会被Python垃圾回收机制回收,导致界面上图标显示空白
  • 如果提取图标失败,优先检查传入路径是否有读取权限、目标文件是否为有效的Win32可执行文件

内容的提问来源于stack exchange,提问作者Giannis Tsakas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 00:45:45