Pyinstaller 打包 Tkinter 程序時引入圖標解決方法


Pyinstaller 打包 Tkinter 程序時引入圖標解決方法

描述

在windows下開發python的gui程序時,多數使用pyinstaller, py2exe等打包工具.
在因為tkinter框架時,代碼中使用iconbitmap引入程序框的圖標樣式,直接運行時沒有問題,
但是在pyinstaller打包后會出現無法找到ico文件問題.
網上參考了幾個解決方法都過於復雜(img2py, 或者修改spec打包參數)
下面我為大家帶來一個非常方便可行的辦法.

from Tkinter import *
root = Tk()
root.iconbitmap("icon.ico")
Label(root, text="hello world").pack()
root.mainloop()

為了適配pyinstaller能把icon文件引入,我們修改成程序,把icon.ico 修改為 icon.py

以下為py3.X適用

import base64
open_icon = open("icon.ico","rb")
b64str = base64.b64encode(open_icon.read())
open_icon.close()
write_data = "img = %s" % b64str
f = open("icon.py","w+")
f.write(wrte_data)
f.close()

 

以下PY2.x適用

from Tkinter import *
import base64
from icon import img

root = Tk()
tmp = open("tmp.ico","wb+")
tmp.write(base64.b64decode(img))
tmp.close()
root.iconbitmap("tmp.ico")
os.remove("tmp.ico")

Label(root, text="hello world").pack()
root.mainloop()

 

修改 hello.py源碼,導入icon.py中的img, 創建一個臨時的tmp.ico文件作為圖標引入后刪除即可

from Tkinter import *
import base64
from icon import img

root = Tk()
tmp = open("tmp.ico","wb+")
tmp.write(base64.b64decode(img))
tmp.close()
root.iconbitmap("tmp.ico")
os.remove("tmp.ico")

Label(root, text="hello world").pack()
root.mainloop()

最后使用pyinstaller打包即可

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM