PyInstaller打包tkinter UI介面icon

Posted in :

2個步驟可以做到這個功能,但似乎有其他簡單一點的做法,PyInstaller 應該可以打包外部資源檔案進去。

檔案內容轉成String

icon_to_py.py:

import base64
icon = open('test.ico','rb')
b64str = base64.b64encode(icon.read())
icon.close()
data = "iconImg = '%s'" %b64str
f = open('icon.py', 'w+')
f.write(data)
f.close()

tkinter GUI 主程式

gui.py

import tkinter as tk
import base64, os
root = tk.Tk()
iconImg = 'Base64Data'
tmpIcon = open('tmp.ico', 'wb+')
tmpIcon.write(base64.b64decode(iconImg))
tmpIcon.close()
root.iconbitmap('tmp.ico')
os.remove('tmp.ico')
root.mainloop()

上面的寫法,無法套用到 macOS 和 Linux, Linux 解法:

tmpIcon = open(icon_filepath, 'wb+')
tmpIcon.write(base64.b64decode(iconImg))
tmpIcon.close()
if platform.system() == 'Windows':
    root.iconbitmap(icon_filepath)
if platform.system() == 'Darwin':
    from PIL import Image, ImageTk
    logo = ImageTk.PhotoImage(Image.open(icon_filepath).convert('RGB'))
    root.call('wm', 'iconphoto', root._w, logo)
if platform.system() == 'Linux':
    logo = PhotoImage(file=icon_filepath)
    root.call('wm', 'iconphoto', root._w, logo)
os.remove(icon_filepath)

附註:Linux 的 icon 直接使用的是圖片PNG 格式即可,不需使用 icon format.


PyInstaller 打包說明:
https://pyinstaller.readthedocs.io/en/stable/usage.html

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *