问题
This python27 32bit code runs perfectly in IDLE, but when packaged by py2exe... not so good. This is not a duplicate of the missing Tk() question. Something else appears to be uninitialized when running the py2exe generated executable, the call at ImageTk.PhotoImage() balks with 'too early to create image':
C:\python\python_ui\exe\dist>basic.exe
Traceback (most recent call last):
File "basic.py", line 7, in <module>
File "PIL\ImageTk.pyo", line 117, in __init__
File "Tkinter.pyo", line 3367, in __init__
File "Tkinter.pyo", line 3304, in __init__
RuntimeError: Too early to create image
Exception AttributeError: "'PhotoImage' object has no attribute '_PhotoImage__photo'" in <bound method PhotoImage.__del__ of <PIL.ImageTk.Ph
otoImage object at 0x02CA3A90>> ignored
basic.py - very basic example and yes, Tk() is initialized. Also, the module versions appear to match in both IDLE() and the executable version
from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
image = Image.open("background.jpg")
photo = ImageTk.PhotoImage(image)
label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()
root.mainloop()
setup.py - Here is my py2exe setup, and I run python setup.py py2exe
to get the executable:
import py2exe, sys, os
from distutils.core import setup
from glob import glob
sys.path.append("C:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\redist\\x86\\Microsoft.VC90.CRT")
sys.argv.append('py2exe')
setup(
data_files = [
("Microsoft.VC90.CRT", glob(r'C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT\*.*')),
("background.jpg"),
],
options = {
'py2exe' : {
'compressed': 1,
'optimize': 2,
'bundle_files': 3,
'dist_dir': 'dist',
'dll_excludes': ["MSVCP90.dll"]
}
},
zipfile=None,
console = [{'script':'user_code.py'}, {'script':'basic.py'}],
)
Version Information matches, and printing the image gives same values when run from IDLE() as it does the executable:
- pil 3.4.2
- tkinter $Revision: 81008 $
- PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=179x119 at 0x3DF6A50
回答1:
When all else fails, rebuild everything...
- Uninstall 32bit python27.12
- install 32bit python27.10 // 12 will probably work too
- pip install pip
- pip install Pillow
- install MSVC9
- pip install py2exe
- remove all prior distribution builds from older py2exe
- regenerate executable
It works!
来源:https://stackoverflow.com/questions/41031806/py2exe-gives-runtimeerror-too-early-to-create-image