我正在使用python(我的版本是2.7
)。我想将图像添加到GUI(Tkinter
),然后使用pyinstaller
转换为可执行格式。
我遵循了SO上的要求,也遵循了ActiveState上的要求
当我在代码中提及图片的路径时,仅当我直接运行它时它才起作用。如果我将其转换为exe
,它将无法打开。
如其他解决方案所述更改代码,例如通过将其转换为编码的字符串,它可以在linux上正常运行。但是在Windows上会引发错误
码:
from Tkinter import *
from PIL import ImageTk, Image
logo = '''
----- encoded string -----
'''
root = Tk()
logoimage = Tkinter.PhotoImage(master=root, data=logo)
Label(root, image=logoimage).pack()
root.mainloop()
变更1:
上面的代码在Linux上有效。在Windows上,我在
logoimage = Tkinter.PhotoImage(master=root, data=logo)
行上收到错误NameError: name 'Tkinter' is not defined
变更2:
所以我尝试将行更改为
logoimage = ImageTk.PhotoImage(master=root, data=logo)
。我得到的错误是File "C:\Python27\lib\site-packages\PIL\ImageTk.py", line 88, in __init__
image = Image.open(BytesIO(kw["data"]))
File "C:\Python27\lib\site-packages\PIL\Image.py", line 2330, in open
% (filename if filename else fp))
IOError: cannot identify image file <_io.BytesIO object at 0x00000000024BB150>
Exception AttributeError: "'PhotoImage' object has no attribute '_PhotoImage__photo'" in <bound method PhotoImage.__del__ of <PIL.ImageTk.PhotoImage object at 0x00000000024D49E8>> ignored
变更3:
但是,如果我将行更改为
iconImage= ImageTk.PhotoImage(Image.open('path_to_image.png'))
。仅当我直接运行时它才有效。如果我将其转换为可执行文件,则控制台将打开2-3秒,并显示诸如Unable to locate the image file
之类的错误 最佳答案
显式地进行解码和转换可能比您当前正在执行的功能更强大。此代码在Linux上的Python 2.6.6上有效。
import io, base64
from Tkinter import *
from PIL import ImageTk, Image
#A simple 64x64 PNG fading from orange in the top left corner
# to red in the bottom right, encoded in base64
logo_b64 = '''
iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIA
AAAlC+aJAAAA/0lEQVR4nO3Zyw7CMAxEUdP//+W2rCqBoJA2noclS1kn9yjLeex7xKY76+
wNS+l6KSCjXgdIqhcB8uoVgNR6OiC7ngsA1BMBmHoWAFZPASDr8QBwPRiAr0cCKPUwAKse
AyDWAwDc+mwAvT4VoKjPA4jqkwC6+gyAtD7WSYC6fu4HDOonAB71dwE29bcATvXXAWb1Fw
F+9VcAlvXDANf6MYBx/QDAu/4fwL7+J6BC/TmgSP0JoE79N0Cp+g9Atfp3QMH6F0DN+gNQ
tj62WErXB2PgQNZLAb3U6wC91OsAvdTrAL3U6wC91OsAvdTrAL3U6wC91OsAvdTrAL3Uz7
z+BNmX4gqbppsaAAAAAElFTkSuQmCC
'''
#Decode the PNG data & "wrap" it into a file-like object
fh = io.BytesIO(base64.b64decode(logo_b64))
#Create a PIL image from the PNG data
img = Image.open(fh, mode='r')
#We must open the window before calling ImageTk.PhotoImage
root = Tk()
photo = ImageTk.PhotoImage(image=img)
Label(root, image=photo).pack()
Label(root, text='An embedded\nbase64-encoded PNG').pack()
root.mainloop()
供参考,这是嵌入式PNG的外观。