在 Tkinter 中设置图标

Set Icon in Tkinter

我想用我自己的替换 Tkinter 图标,但其他问题的答案没有帮助。在同一文件夹中,我将我的脚本和使用 Paint 创建的图像保存为 icon.png。这是脚本:

from Tkinter import *

root = Tk()

icon = PhotoImage(file='icon.png')
root.tk.call('wm', 'iconphoto', root._w, icon)

root.mainloop()

此错误是由 root.tk.call 方法造成的:

TclError: couldn't recognize data in image file "icon.png"

错误实际上出现在 root.tk.call... 上方的行 icon = PhotoImage... - 它试图将文件数据读入 PhotoImage 对象但失败了。

Tkinter 本身不支持 PNG 文件类型。您需要使用受支持的文件类型,例如 GIF。如果您想从包括 PNG 在内的多种文件类型中进行选择,我建议安装 Pillow,PIL ("Python Imaging Library") 的 up-to-date 分支。但是,最简单的方法可能是再次在“画图”中打开图像,这次将其另存为 GIF,然后使用它。