使用cx_freeze将脚本转换为.exe时如何包含tkinter?

时间:2017-03-28 02:02:30

标签: python tkinter cx-freeze

我正在使用cx_freeze将python文件传输到exe。问题是当我在setup.py中排除tkinter时,我可以成功生成exe文件,但是当执行exe文件时,它会显示No Module named tkinter

build_exe_options = {"packages": ["os","numpy","time","optparse","linecache","pandas",
                     "matplotlib","PIL"], "excludes": ["tkinter"]}

但是当我尝试包含tkinter时,它就无法生成exe文件。

build_exe_options = {"packages": ["os","numpy","time","optparse","linecache","pandas",
                     "matplotlib","PIL","tkinter"]}
File "C:\Users\changchun_xu\AppData\Local\Programs\Python\Python36-32\lib\os.py", line 669, in __getitem__
    raise KeyError(key) from None
KeyError: 'TCL_LIBRARY'

1 个答案:

答案 0 :(得分:9)

您必须对setup.py进行两次修改才能让事情顺利进行:

  1. 设置TCL-LIBRARYTK_LIBRARY个环境变量。 (你已经这样做了)

  2. tcl86t.dlltk86t.dll添加到 include_files 参数

  3. 所以setup.py应该是这样的:

    import os
    from cx_Freeze import setup, Executable
    
    os.environ['TCL_LIBRARY'] = 'c:/python36/tcl/tcl8.6'
    os.environ['TK_LIBRARY'] = 'c:/python36/tcl/tk8.6'
    
    # Dependencies are automatically detected, but it might need
    # fine tuning.
    buildOptions = dict(
        packages = [],
        excludes = [],
        include_files=['c:/python36/DLLs/tcl86t.dll', 'c:/python36/DLLs/tk86t.dll']
    )
    
    import sys
    base = 'Win32GUI' if sys.platform=='win32' else None
    
    executables = [
        Executable('editor.py', base=base)
    ]
    
    setup(name='editor',
          version = '1.0',
          description = '',
          options = dict(build_exe = buildOptions),
          executables = executables)