Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embed icon in python script

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.

like image 987
maupertius Avatar asked Mar 29 '12 16:03

maupertius


People also ask

How do I add icons to PyInstaller?

Use the --icon argument to specify a custom icon for the application. It will be copied into the Resources folder. (If you do not specify an icon file, PyInstaller supplies a file icon-windowed.

How do I change the icon of a .PY file?

In windows, all files with . py extension have the python icon. You cannot change that for a particular py file. It is, after all, just a textual file.


2 Answers

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!

like image 180
Saúl Pilatowsky-Cameo Avatar answered Sep 25 '22 15:09

Saúl Pilatowsky-Cameo


You probably don't need this but somebody else might find this useful, I found you can do it without creating a file:

import Tkinter as tk

icon = """
    REPLACE THIS WITH YOUR BASE64 VERSION OF THE ICON
    """

root = tk.Tk()
img = tk.PhotoImage(data=icon)
root.tk.call('wm', 'iconphoto', root._w, img)
like image 27
freakrho Avatar answered Sep 23 '22 15:09

freakrho