Embed icon in python script

maupertius picture maupertius · Mar 29, 2012 · Viewed 12.9k times · Source

Does anybody know a way to embed an icon in a Python script such that when I create my standalone executable (using pyinstaller) I don't need to include the .ico file? I know this is possible with py2exe, but in my case I have to use Pyinstaller, as I was not successful using the former. I am using Tkinter.

I know about iconbitmap(iconName.ico) but that doesn't work if I wanna make a onefile executable.

Answer

Saulpila picture Saulpila · Apr 15, 2012

Actually the function iconbitmap can only receive a filename as argument, so there needs to be a file there. You can make a Base64 version of the icon (A string version) following the link, uploading the file and copying the result in your source file as a variable string. Extract it to a temporal file, finally passing that file to iconbitmap and deleting it. It's quite simple:

import base64
import os
from Tkinter import *
##The Base64 icon version as a string
icon = \
""" REPLACE THIS WITH YOUR BASE64 VERSION OF THE ICON
"""
icondata= base64.b64decode(icon)
## The temp file is icon.ico
tempFile= "icon.ico"
iconfile= open(tempFile,"wb")
## Extract the icon
iconfile.write(icondata)
iconfile.close()
root = Tk()
root.wm_iconbitmap(tempFile)
## Delete the tempfile
os.remove(tempFile)

Hope it helps!