Embedding ICO Icons in Tkinter

Although Tkinter is fairly basic, it is still quite convenient when developing some graphical gadgets with Python. Since the native icon is rather plain, a custom icon is generally chosen instead, but then a single-file executable program also has to be shipped with an ICO file to display the icon, which is undoubtedly cumbersome. This article describes how to embed the icon into the executable file.

Steps

Jessie Wilson’s question “Embed icon in python script” on StackOverflow provides a solution:

1
2
3
4
5
6
7
8
import Tkinter as tk

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

root = tk.Tk() 
root.iconphoto(True, tk.PhotoImage(data=icon_png))

The icon is required to be a .png file. The code that implements the image-to-Base64 encoding conversion is as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
"""ico icon"""
import base64


def image_to_base64(image_path):
    with open(image_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
    return encoded_string


icon_png = """
base64 code
"""

if __name__ == "__main__":
    print(image_to_base64("icon.png"))

References