python 3.4 py2exe image.open找不到图像

时间:2015-02-02 04:35:05

标签: python image tkinter exe py2exe

我正在尝试创建一个GUI的可执行文件(使用我的计算机中的12个图像)但是当我创建它时,.exe不会在另一台计算机上运行,​​因为它无法找到这12个图像

我有一棵这样的树

project (folder)
--mycode.py (python file)
--setup.py (python file)
--images (folder)
  --image1 (image .jpg)
  --image2 (image .jpg)
  --image3 (image .jpg)

然后我用py2exe创建.exe,我的树现在是

project (folder)
--__pycache__ (folder)
  --mycode.cpython-34.pyc
--dist (folder)
  --mycode.exe (executable file for windows)
  --(and other 22 elements)
--mycode.py (python file)
--setup.py (python file)
--images (folder)
  --Im_0.jpg
  --Im_1.jpg
  --Im_2.jpg
  --...

现在

我正在使用这些来查找我的图片

import os
scriptDir = os.path.dirname(os.path.realpath(__file__))
IM0 = os.path.join(scriptDir, 'Images\\Im_0.jpg')
....

然后我创建了.exe

然而,当我运行可执行文件时,它说

"NameError: name '__file__' is not defined" 

然后我尝试去http://www.py2exe.org/index.cgi/WhereAmI 因为py2exe没有文件属性

他们说使用

import os
import jpath

if hasattr(sys,"frozen") and sys.frozen in ("windows_exe", "console_exe"):
  p=jpath.path(os.path.abspath(sys.executable)).dirname()

其他人说

import JPath class
import JPath.engine #@UnresolvedImport    
import jpath.syntax
from jpath.data import Boolean, Item, List, Map, Null, Number, Pair, String
import jpath.errors as errors
from jpath.utils.messages import JPATH_INTERNAL_ERROR_MESSAGE
from jpath.utils.text import trimTo
import jpath.evaluators
import re
from linearclassification.lib.utils import jpath,chunk,contains,has_subsequence

但python显示此消息

ImportError: No module named 'JPath'

现在我不知道如何运行我的代码导入与我的树显示的.exe相同的文件夹中的图像

1 个答案:

答案 0 :(得分:1)

完成,答案就是这个

首先在mycode.py中输入

p=os.path.abspath(sys.executable)
IM0 = os.path.join('Images\\Im_0.jpg')
IM1 = os.path.join('Images\\Im_1.jpg')
IM2 = os.path.join('Images\\Im_2.jpg')
...

然后我通过使用setup.py调用mycode.py来创建.exe 像这样

from distutils.core import setup
import py2exe
setup(
 name="mycode",
 windows =['mycode.py'],
 options = {"py2exe": {"packages": ["encodings"]}}
 )

然后我转到命令提示符将目录更改为setup.py和mycode.py所在的文件夹 后者我写了

python setup.py py2exe

创建2个文件夹

--__pycache__ (folder)
  --mycode.cpython-34.pyc
--dist (folder)
  --mycode.exe (executable file for windows)
  --(and other 22 elements)

现在在dist(文件夹)里面我粘贴文件夹Images(文件夹),我的所有图片都是

--dist (folder)
  --mycode.exe (executable file for windows)
  --(and other 22 elements)
  --Images (folder)
    --Im_0.jpg
    --Im_1.jpg
    --Im_2.jpg
    --....

完成

如果有人有更好的方法,请告诉我

非常感谢