Python 的 Qt 和 Briefcase¶
Briefcase 是一个打包工具,允许你为Python应用程序创建一个独立的包。它支持以下安装程序格式:
.appmacOS 应用程序包适用于Windows的MSI安装程序
适用于Linux的AppImage
更多详情,请参阅官方文档。
Qt 6 支持状态¶
截至2021年3月,Qt 6尚未得到支持。
准备¶
使用以下pip命令安装Briefcase:
pip install briefcase
你还需要:在Linux上的docker,在Windows上的WixToolset,
如果您使用的是虚拟环境,请记得在安装Briefcase之前激活它。
安装后,briefcase 二进制文件位于您的虚拟环境的 bin/ 目录中,或者您的 Python 可执行文件所在的位置。
你可以使用briefcase助手创建一个全新的项目,或者设置你自己的项目。
使用Briefcase助手¶
运行以下命令并回答问题以开始:
briefcase new
确保选择PySide6作为GUI工具包选择。 您的PySide6应用程序现已配置完成。您可以跳转到构建包。
设置你的项目¶
创建一个pyproject.toml¶
在项目的根目录下,创建一个 pyproject.toml 文件:
[tool.briefcase]
project_name = "MyPySideApp"
bundle = "com.example"
version = "0.0.1"
url = "https://somwhere/on/the/net"
license = "GNU General Public License v3 (GPLv3)"
author = 'MyName Firstname'
author_email = "cool@mailexample.com"
[tool.briefcase.app.mypysideapp]
formal_name = "A Cool App"
description = "The coolest app ever"
icon = "src/mypysideapp/resources/appicon" # Briecase will choose the right extension depending the os (png,ico,...)
sources = ['src/mypysideapp']
requires = ['pyside6==6.0.0',
'pony>=0.7.11,<0.8',
'dickens==1.0.1',
'Pillow==7.1.2',
'mako==1.1.2',
'beautifulsoup4']
[tool.briefcase.app.mypysideapp.macOS]
requires = []
[tool.briefcase.app.mypysideapp.linux]
requires = []
system_requires = []
[tool.briefcase.app.mypysideapp.windows]
requires = []
编写一些代码¶
假设你的项目结构是这样的:
pyproject.toml
setup.cfg
pytest.ini
src/
mypysideapp/
resources/
appicon.png
appicon.ico
__init__.py
__main__.py
app.py
__main__.py 的内容:
import sys
from PySide6.QtWidgets import QApplication
from mypysideapp.app import MyWidget
if __name__ == "__main__":
app = QApplication(sys.argv)
widget = MyWidget()
widget.resize(800, 600)
widget.show()
sys.exit(app.exec())
app.py 的内容:
import random
from PySide6.QtWidgets import (QLabel, QPushButton,
QVBoxLayout, QWidget)
from PySide6.QtCore import Slot, Qt
class MyWidget(QWidget):
def __init__(self):
QWidget.__init__(self)
self.hello = ["Hallo Welt", "你好,世界", "Hei maailma",
"Hola Mundo", "Привет мир"]
self.button = QPushButton("Click me!")
self.text = QLabel("Hello World")
self.text.setAlignment(Qt.AlignCenter)
self.layout = QVBoxLayout()
self.layout.addWidget(self.text)
self.layout.addWidget(self.button)
self.setLayout(self.layout)
# Connecting the signal
self.button.clicked.connect(self.magic)
@Slot()
def magic(self):
self.text.setText(random.choice(self.hello))
构建包¶
初始化包¶
只需运行:
briefcase create
运行以下命令以初始化为Windows、Linux和macOS构建包。
它为不同的平台各自创建一个子目录。
此步骤需要更长时间,因为它添加了pyproject.toml文件中requires部分列出的包。
构建应用程序¶
briefcase build
您将获得:
macOS/A Cool App/A Cool App.app
or
linux/A Cool App-x86_64-0.0.1.AppImage
or
windows\A Cool App
运行应用程序¶
briefcase run
注意
你可以在dev模式下运行你的项目(你的源代码未打包),使用
briefcase dev
构建安装程序(仅限Windows和macOS)¶
macOS:
briefcase package --no-sign
可以签名,请参阅
文档。
你会得到 macOS/A Cool App-0.0.1.dmg
Windows:
briefcase package
你得到 windows\A_Cool_App-0.0.1.msi