2017-02-11 35 views
0

我正在寫一個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 
+0

你使用的是python2還是python3?根據這[問題](http://stackoverflow.com/questions/27175029/tkinter-will-not-recognize-image-data-in-base64-encoded-string)它似乎可能與python3。 –

+0

@ j_4321我正在使用Python 3.我檢查了這個問題,它似乎並沒有解決我的問題。 –

+0

所以你有沒有嘗試[問題](http://stackoverflow.com/questions/27175029/tkinter-will-not-recognize-image-data-in-base64-encoded-string)給出的代碼? –

回答

1

Tkinter的PhotoImage類(在Python 3用TK 8.6)只能讀取GIF,PGM/PPM和PNG圖像格式。有兩種方法來讀取圖像:

  • 從一個文件:PhotoImage(file="path/to/image.png")
  • 從base64編碼字符串:PhotoImage(data=image_data_base64_encoded_string)

首先,如果你想將圖像轉換成base64-編碼字符串:

import base64 

with open("path/to/image.png", "rb") as image_file: 
    image_data_base64_encoded_string = base64.b64encode(image_file.read()) 

然後用它在Tkinter的:

import tkinter as tk 

root = tk.Tk() 

im = PhotoImage(data=image_data_base64_encoded_string) 

tk.Label(root, image=im).pack() 

root.mainloop() 

我認爲你的問題是你在PhotoImage之前使用datas= base64.b64decode(base64_encodedString)解碼字符串,而你應該直接使用base64_encodedString

+0

事實上,錯誤是你所猜測的,我用解碼值來創建圖像對象。謝謝 ! –

相關問題