首页 > 解决方案 > Cx_Freeze 构建没有错误,但 exe 没有打开

问题描述

我正在尝试使用 cx_Freeze 构建一个 exe,它使用多个模块:

import tkinter as tk
from tkinter import ttk
import random, time, bluetooth, json, sys, os
from _thread import *
from threading import Thread, Lock

当我尝试构建 exe 时,它​​似乎运行良好:它不会引发任何错误并创建包含 exe 文件的构建文件夹。但是,当我尝试打开 exe 文件时,它根本无法打开。如果短暂地似乎闪烁一个窗口,但随后消失。我的 setup.py 是这样的:

from cx_Freeze import setup,Executable
import sys
import os

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')

includes = []
include_files = []
packages = []
base = "Win32GUI"
setup(
    name = 'Buzzer',
    version = '0.1',
    description = 'Buzzer application',
    author = 'Me',
    executables = [Executable('Buzzer.py')]
)

闪烁的屏幕包含以下回溯:

回溯(最近一次调用最后):文件“C:\Users\X\AppData\Local\Programs\Python\Python37\lib\site-packages\cx_Freeze\initscripts__startup__.py”,第 14 行,运行 module.run()文件“C:\Users\X\AppData\Local\Programs\Python\Python37\lib\site-packages\cx_Freeze\initscripts\Console.py”,第 26 行,运行 exec(code, m. dict ) 文件“打印.py", line 1, in File "C:\Users\X\AppData\Local\Programs\Python\Python37\lib\tkinter__init__.py", line 36, in import _tkinter # 如果失败,您的 Python 可能未配置对于 Tk ImportError: DLL load failed: 找不到指定的模块。

标签: pythondllbuildexecx-freeze

解决方案


您需要告诉cx_Freeze在构建目录中包含 TCL 和 TK DLL。

对于cx_Freeze 5.1.1(当前版本)或5.1.0,DLL 需要包含在lib构建目录的子目录中。您可以通过将元组传递给列表选项(source, destination)的相应条目来做到这一点:include_files

include_files = [(os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tk86t.dll'), os.path.join('lib', 'tk86t.dll')),
                 (os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tcl86t.dll'), os.path.join('lib', 'tcl86t.dll'))]

您需要将此include_files列表传递给build_exesetup 调用中的选项(并且您还应该将base您定义的传递给Executable):

setup(
    name = 'Buzzer',
    version = '0.1',
    description = 'Buzzer application',
    author = 'Me',
    options={'build_exe': {'include_files': include_files}},
    executables = [Executable('Buzzer.py', base=base)]
)

对于其他cx_Freeze版本,DLL 需要直接包含在构建目录中。这可以通过以下方式完成:

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

推荐阅读