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

Windows下获取文件类型系统图标并适配Tkinter的技术求助

Windows下获取文件类型系统图标并适配Tkinter的实现方案

核心思路

通过pywin32调用Windows系统API提取文件类型关联图标,再用Pillow将位图转换为Tkinter支持的PhotoImage格式。

具体实现代码

import win32gui
import win32ui
import win32con
from PIL import Image, ImageTk
import tkinter as tk

def get_filetype_icon(ext, size=16):
    # 构造虚拟文件路径用于获取关联图标
    dummy_file = f"dummy{ext}"
    # 提取大、小尺寸的图标句柄
    large_icon_handles, small_icon_handles = win32gui.ExtractIconEx(dummy_file, 0)
    
    # 根据指定尺寸选择对应图标句柄
    target_handle = small_icon_handles[0] if size <= 16 else large_icon_handles[0]
    
    # 创建设备上下文与位图对象
    dc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
    bmp = win32ui.CreateBitmap()
    bmp.CreateCompatibleBitmap(dc, size, size)
    hdc = dc.CreateCompatibleDC()
    
    # 将图标绘制到位图中
    win32gui.DrawIconEx(hdc.GetHandleOutput(), 0, 0, target_handle, size, size, 0, None, win32con.DI_NORMAL)
    
    # 把Windows位图转换为Pillow图像
    bmp_info = bmp.GetInfo()
    bmp_data = bmp.GetBitmapBits(True)
    img = Image.frombuffer(
        "RGBA",
        (bmp_info['bmWidth'], bmp_info['bmHeight']),
        bmp_data, 'raw', 'BGRA', 0, 1
    )
    
    # 释放Windows API资源,避免内存泄漏
    win32gui.DestroyIcon(target_handle)
    hdc.DeleteDC()
    win32gui.ReleaseDC(0, dc.GetHandleOutput())
    win32gui.DeleteObject(bmp.GetHandle())
    
    # 转换为Tkinter可直接使用的PhotoImage对象
    return ImageTk.PhotoImage(img)

# 测试示例
root = tk.Tk()
root.title("文件类型图标展示")

# 获取PNG格式的32x32图标并显示
png_icon = get_filetype_icon(".png", size=32)
icon_label = tk.Label(root, image=png_icon)
icon_label.pack(padx=20, pady=20)

root.mainloop()

关键注意事项

  • 依赖安装:先执行pip install pywin32 pillow安装所需库
  • 尺寸适配:Windows默认提供16x16(小图标)和32x32(大图标)两种规格,可按需调整size参数
  • 资源释放:必须手动销毁API创建的句柄和对象,防止内存占用过高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 16:18:25