本文介绍了py2exe给RuntimeError:创建图像还为时过早的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此python27 32位代码在IDLE中可完美运行,但是当由py2exe打包时...不太好.这不是丢失的Tk()问题的重复.运行py2exe生成的可执行文件时,似乎还有其他未初始化的情况,对ImageTk.PhotoImage()的调用使太早创建图像"成为现实:

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 -非常简单的示例,是的,Tk()已初始化.而且,模块版本在IDLE()和可执行版本中似乎都匹配

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

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

版本信息匹配,并且从IDLE()运行时,与可执行文件一样,打印图像时会提供相同的值:

Version Information matches, and printing the image gives same values when run from IDLE() as it does the executable:

  • pil 3.4.2
  • tkinter $修订版:81008 $
  • PIL.JpegImagePlugin.JpegImageFile图像模式= RGB大小= 179x119在0x3DF6A50处

推荐答案

当所有其他方法都失败时,重新构建所有内容...

When all else fails, rebuild everything...

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

有效!

这篇关于py2exe给RuntimeError:创建图像还为时过早的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 18:32