根据您的问题,您可以假定您的项目结构如下:
├── index.html├── jquery.js├── main.py├── my_custom.js└── styles.css
对于您的情况,有2个选项:
使用
--add-data
import os
import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
def resource_path(relative_path):
“”” Get absolute path to resource, works for dev and for PyInstaller “”“
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(“.”)return os.path.join(base_path, relative_path)
if name == “main”:
import sysapp = QtWidgets.QApplication(sys.argv)view = QtWebEngineWidgets.QWebEngineView()filename = resource_path("index.html")url = QtCore.QUrl.fromLocalFile(filename)view.load(url)view.show()sys.exit(app.exec_())
如果要将外部资源添加到可执行文件,则必须使用“ –add-data”选项:
pyinstaller --onefile --windowed --add-data="index.html:." --add-data="jquery.js:." --add-data="my_custom.js:." --add-data="styles.css:." main.py
对于Windows,将“:”更改为“;”。
- 使用
.qrc
使用此方法,您将使用pyrcc5将文件(.html,.css,.js等)转换为.py代码,为此,您必须执行以下步骤:
2.1。在项目文件夹中创建一个名为resource.qrc的文件,其中包含以下内容:
<RCC> <qresource prefix="/"> <file>index.html</file> <file>jquery.js</file> <file>my_custom.js</file> <file>styles.css</file> </qresource></RCC>
2.2使用pyrcc5将其转换为.py:
pyrcc5 resource.qrc -o resource_rc.py
2.3导入resource_rc.py文件,并在main.py文件中使用带有模式“ qrc”的url:
import osimport sysfrom PyQt5 import QtCore, QtWidgets, QtWebEngineWidgetsimport resource_rcif __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) view = QtWebEngineWidgets.QWebEngineView() url = QtCore.QUrl("qrc:/index.html") view.load(url) view.show() sys.exit(app.exec_())
2.4使用初始命令编译项目
pyinstaller --onefile --windowed main.py
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)