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

How to include tkinter when using cx_freeze to convert script to .exe?

我正在使用 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'

您必须对您的 setup.py 进行两次修改才能正常工作:

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

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

所以 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)