使用 cx_freeze 冻结 py 脚本时出现问题

Issue when freezing a py script with cx_freeze

我刚刚在 Python 中担任编码并想使用 cx freeze 创建一个独立的 .exe,但我遇到了 tkinter 的问题。我能够生成一个非常简单的 window 但是当我添加 tkinter 时,它不再起作用了。

这是我的代码:

tkinter2.py:

    #!/usr/bin/env python
    # -*-coding:Latin-1 -*


    import tkinter 

    base = None

    if sys.platform  == 'win32':
        base="Win32GUI"

    TK=Tk()

    # Function called when user hit the keyboard
    def clavier(event):
        global coords

        touche = event.keysym

        if touche == "Up":
            coords = (coords[0], coords[1] - 10)
        elif touche == "Down":
            coords = (coords[0], coords[1] + 10)
        elif touche == "Right":
            coords = (coords[0] + 10, coords[1])
        elif touche == "Left":
            coords = (coords[0] -10, coords[1])
        # change of coordinates for the rectangle
        canvas.coords(rectangle, coords[0], coords[1], coords[0]+25, coords[1]+25)

    # canvas creation
    canvas = Canvas(TK, width=250, height=250, bg="ivory")
    # initial coord
    coords = (0, 0)
    #rectangle creation
    rectangle = canvas.create_rectangle(0,0,25,25,fill="violet")
    canvas.focus_set()
    canvas.bind("<Key>", clavier)
    # canvas creation
    canvas.pack()

然后在cmd中,我是这样做的: 我转到 C:\Python34 并点击 python.exe "Scripts\cxfreeze" "Scripts\tkinter2.py" 它似乎可以编译,但表示缺少某些模块,这似乎是 tkinter。如果我启动创建的 .exe,我有 "ImportError: no module name 'Tkinter'"。 我使用的是 Python 3.4 并安装了相应的 cx_freeze.

你知道我为什么会出现这样的错误吗?是因为冻结我的py脚本时tkinter的某些底层组件无法使用吗?

谢谢, StaP

通常在使用 CX_Freeze 时,您会创建一个 setup.py 文件(您可以将其重命名为任何您想要的名称)。然后构建你通常会做 'python setup.py build'(这是在命令提示符下,你会 cd 到 setup.py 和 tkinter2.py 文件存储的目录)。 Tk 无法使用 cx freeze 构建的最常见原因是您缺少 DLL 文件。用下面的代码制作一个 setup.py 并尝试一下:

import sys
import cx_Freeze
import os.path


base = None

if sys.platform == 'win32':
    base = "Win32GUI"


PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))
os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6')
os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6')

executables = [cx_Freeze.Executable("tkinter2.py", base=base)]


options = {
    'build_exe': {

        'include_files':[
            os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tk86t.dll'),
            os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tcl86t.dll'),


         ],
    },

}

cx_Freeze.setup(
    name = "Stack Overflow Q",
    options = options,
    version = "1.0",
    description = 'Stack Overflow Q',
    executables = executables
)

编辑:我还注意到你的程序末尾没有 TK.mainloop()