Insert icon in python script

Does anyone know a way to insert an icon in a Python script so that when creating 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 since I was not able to use the first one. I am using Tkinter.

I know about iconbitmap(iconName.ico), but this does not work if I want to make onefile executable.

+7
source share
3 answers

In fact, the iconbitmap function can only accept a file name as an argument, so there should be a file there. You can make the Base64 version of the icon (string version) via the link, download the file and copy the result to the source file as a variable string. Extract it to a temporary file, and finally transfer this file to iconbitmap and delete it. It is pretty 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 this helps!

+7
source

You probably don't need this, but someone might find this useful, I found that you can do this 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)
+6
source

ALI3N

:

  • .spec :
a = Analysis(....)
pyz = PYZ(a.pure)
exe = EXE(pyz,
          a.scripts,
          a.binaries + [('your.ico', 'path_to_your.ico', 'DATA')], 
          a.zipfiles,
          a.datas, 
          name=....
       )
  1. script:
datafile = "your.ico" 
if not hasattr(sys, "frozen"):
    datafile = os.path.join(os.path.dirname(__file__), datafile) 
else:  
    datafile = os.path.join(sys.prefix, datafile)
  1. :
root = tk.Tk()
root.iconbitmap(default=datafile)

, script Pyinstaller:

root = tk.Tk()
root.iconbitmap(default="path/to/your.ico")

My info : python3.4, pyinstaller3.1.1

0
source

All Articles