2014-05-23 13 views
1

我有一個Python腳本,我用Pyinstaller編譯成一個單一的.exe文件。不幸的是,無論是劇本和編譯的文件必須在同一目錄作爲我的.ICO和背景文件(.png)圖像,爲我指的是他們這樣的:在Python中包含圖片數據,可能嗎?

root.iconbitmap("logo.ico") 
background = ImageTk.PhotoImage(Image.open("background.png")) 

它可以包括圖片數據在腳本文件本身中,而不是使其依賴於單個可執行文件之外的文件?我正在使用Tkinter和PIL。

+2

我相信這是在[此帖](http://stackoverflow.com/questions/14129405回答/ python-pyinstaller-and-include-icon-file) http://stackoverflow.com/questions/14129405/python-pyinstaller-and-include-icon-file – Jason

+0

@Jason that's awesome ... I use pyinstaller所有的時間,並不知道關於這個 –

回答

1

至於建議,你可以Base64編碼它:

import base64 

im_filename = 'background.png' 
im_variableName = 'background' 
py_filename = 'embeddedImage.py' 

with open(im_filename,'rb') as f: 
    str64 = base64.b64encode(f.read()) 

with open(py_filename,'w') as f: 
    f.write('%s="%s"'%(im_variable_name,str64)) 

然後:

from PIL import Image 
import cStringIO 
import base64 

from embeddedImage import background 
# or copy paste the background variable found in embeddedImage.py 
im = Image.open(cStringIO.StringIO(base64.b64decode(background))) 
3

只要通過base64編碼,您可以在任何腳本中包含任何合理大小的文件。然後你將它作爲一個字符串存儲。

+4

+1,因爲這是100%正確的......但是你至少可以把他連接到能幫助他進一步的事情上(比如http://code.activestate.com/recipes/52264-inline-gifs-with -tkinter /) –

相關問題