我正在寫一個tkinter程序,利用一些JPG文件的背景。但是,我發現使用「pyinstaller」將腳本轉換爲.exe文件時,用於tkinter窗口的圖像不會編譯/添加到.exe文件。如何在Tkinter標籤中使用base64編碼的圖像字符串?
因此,我決定在Python腳本中對圖像進行硬編碼,以便不存在外部依賴性。爲此,我做了以下事情:
import base64
base64_encodedString= ''' b'hAnNH65gHSJ ......(continues...) '''
datas= base64.b64decode(base64_encodedString)
上述代碼用於解碼base64編碼的圖像數據。 我想使用這個解碼的圖像數據作爲圖片使用,並顯示爲tkinter中的標籤/按鈕。
例如:
from tkinter import *
root=Tk()
l=Label(root,image=image=PhotoImage(data=datas)).pack()
root.mainloop()
然而,Tkinter的不接受存儲在data
的值被用作圖像。 它顯示以下錯誤 -
Traceback (most recent call last):
File "test.py", line 23, in <module>
l=Label(root,image=PhotoImage(data=datas))
File "C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 3394, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 3350, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize image data
你使用的是python2還是python3?根據這[問題](http://stackoverflow.com/questions/27175029/tkinter-will-not-recognize-image-data-in-base64-encoded-string)它似乎可能與python3。 –
@ j_4321我正在使用Python 3.我檢查了這個問題,它似乎並沒有解決我的問題。 –
所以你有沒有嘗試[問題](http://stackoverflow.com/questions/27175029/tkinter-will-not-recognize-image-data-in-base64-encoded-string)給出的代碼? –