python - 无法在Windows

时间:2015-08-04 13:48:18

标签: python windows tkinter pyinstaller pillow

我正在使用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

的错误

2 个答案:

答案 0 :(得分:1)

明确地进行解码和转换可能比您当前所做的更强大。此代码适用于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的样子。

fading from orange in the top left corner to red in the bottom right

答案 1 :(得分:0)

from Tkinter import *
#...
logoimage = Tkinter.PhotoImage(master=root, data=logo)

如果使用import *将Tkinter模块直接转储到全局范围,则不应使用模块名称为类和函数名添加前缀。删除前缀,或删除import *

import Tkinter
#...
logoimage = Tkinter.PhotoImage(master=root, data=logo)

或者

from Tkinter import *
#...
logoimage = PhotoImage(master=root, data=logo)

我怀疑你没有在Linux中收到错误,因为你的Python版本会自动导入常用模块。实际上,所有脚本的顶部都有一个不可见的import Tkinter