cx_freeze 中没有这样的文件或目录:'main.ui'

No such file or directory:'main.ui' in cx_freeze

我用PyQT5开发了一个软件,使用python。 现在我有 main.ui 和 main.py 我使用此命令行读取 main.ui 文件:

FORM_CLASS,_=loadUiType(path.join(path.dirname(__file__),"main.ui"))

现在我的 main.ui 已连接到我的 main.py 文件,其中编写了主要 python 代码。

我还根据 cx_freeze 说明创建了 setup.py

然后我用了cmd命令:

python setup.py build_exe

完成后我收到以下错误:

No such file or directory:'main.ui'

我能解决这个问题吗?

如果您要使用外部资源,那么您应该使用 data files 的 cx_freeze 手册:

Using data files Applications often need data files besides the code, such as icons. Using a setup script, you can list data files or directories in the include_files option to build_exe. They’ll be copied to the build directory alongside the executable. Then to find them, use code like this:

def find_data_file(filename):
    if getattr(sys, 'frozen', False):
        # The application is frozen
        datadir = os.path.dirname(sys.executable)
    else:
        # The application is not frozen
        # Change this bit to match where you store your data files:
        datadir = os.path.dirname(__file__)
    return os.path.join(datadir, filename)

An alternative is to embed data in code, for example by using Qt’s resource system.

因此,在您的情况下,将您的代码修改为:

import os.path
import sys
# ...

def find_data_file(filename):
    if getattr(sys, 'frozen', False):
        # The application is frozen
        datadir = os.path.dirname(sys.executable)
    else:
        # The application is not frozen
        # Change this bit to match where you store your data files:
        datadir = os.path.dirname(__file__)
    return os.path.join(datadir, filename)

# ...

FORM_CLASS,_=loadUiType(<b>find_data_file("main.ui")</b>)

# ...

并更改 setup.py 以包含 .ui:

from cx_Freeze import setup, Executable

setup(
    name="mytest",
    version="0.1",
    description="",
    <b>options={"build_exe": {"include_files": "main.ui"}}</b>,
    executables=[Executable("main.py")],
)