py2exe gives RuntimeError: Too early to create image

py2exe gives RuntimeError: Too early to create image

这个 python27 32 位代码 运行 在 IDLE 中是完美的,但是当被 py2exe 打包时...不太好。这不是缺失的 Tk() 问题的副本。当 运行 生成 py2exe 生成的可执行文件时,其他内容似乎未初始化,ImageTk.PhotoImage() 处的调用因 '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 - 非常基本的示例,是的,Tk() 已初始化。此外,模块版本在 IDLE() 和可执行版本中似乎都匹配

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 - 这是我的 py2exe 设置,我 运行 python setup.py py2exe 获取可执行文件:

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'}],
)

版本信息匹配,打印图像给出与 IDLE() 中的 运行 相同的值,与可执行文件相同:

当一切都失败时,重建一切...

  1. 卸载 32 位 python27.12
  2. 安装 32 位 python27.10 // 12 可能也可以
  3. pip 安装 pip
  4. pip 安装枕头
  5. 安装 MSVC9
  6. pip 安装 py2exe
  7. 从旧的 py2exe 中删除所有先前的分发版本
  8. 重新生成可执行文件

有效!