Python是怎么将Vue项目打包成桌面端应用程序的?看这篇就够了

在不使用 Electron 的情况下,怎么将前端项目(Vue/React)变成一个桌面端 exe 应用程序呢?使用 pywebview + pyinstaller 就可以实现。本文详细介绍如何从零开始创建一个基于 pywebview 的桌面应用,并最终将其打包成独立的可执行文件(exe)。整个过程包括环境搭建、前端集成、Python 交互实现以及打包部署。

安装

powershell 复制代码
pip install pywebview pyinstaller

项目结构

text 复制代码
my_app/
├── web_dist/      # 前端资源目录(Vue/React打包结果)
│   └── dist/
│       ├── index.html
│       ├── style.css
│       └── app.js
├── main.py        # 主程序
└── topackage.py   # 打包脚本

主程序开发 (main.py)

python 复制代码
import webview
from webview import screens

class Api:
    def __init__(self):
        self.cancel_heavy_stuff_flag = False

if __name__ == '__main__':
    screen = screens[0]
    width = screen.width
    height = screen.height
    api = Api()

    webview.settings = {
        'OPEN_DEVTOOLS_IN_DEBUG': True,
    }

    window = webview.create_window(
        '我的应用', './web_dist/dist/index.html', fullscreen=False, width=int(width), height=int(height))
    webview.start(http_server=False, debug=True)

打包脚本 (topackage.py)

python 复制代码
import os
import shutil
import subprocess
from pathlib import Path


def package_app():
    # 1. 检查必要文件是否存在
    if not Path("main.py").exists():
        raise FileNotFoundError("主程序 main.py 不存在")
    if not Path("web_dist/dist/index.html").exists():
        raise FileNotFoundError("前端资源 web_dist/dist/index.html 不存在")

    # 2. 安装 PyInstaller(如果未安装)
    try:
        import PyInstaller
    except ImportError:
        print("正在安装 PyInstaller...")
        subprocess.check_call(["pip", "install", "pyinstaller"])

    # 3. 清理旧构建文件
    build_dir = Path("build")
    dist_dir = Path("dist")
    spec_file = Path("main.spec")

    for path in [build_dir, dist_dir, spec_file]:
        if path.exists():
            if path.is_dir():
                shutil.rmtree(path)
            else:
                path.unlink()

    # 4. 执行打包命令
    cmd = [
        "pyinstaller",
        "--onefile",
        "--windowed",
        "--add-data", "web_dist/dist;web_dist/dist",  # Windows 用分号分隔
        "--name", "MyWebViewApp",
        "main.py"
    ]

    print("开始打包...")
    subprocess.check_call(cmd)

    # 5. 验证结果
    exe_path = dist_dir / "MyWebViewApp.exe"
    if exe_path.exists():
        print(f"\n 打包成功!可执行文件位置: {exe_path.resolve()}")
        print("注意:目标计算机需要安装 WebView2 Runtime")
    else:
        raise RuntimeError("打包失败,请检查错误信息")


if __name__ == "__main__":
    package_app()

打包与运行

执行打包脚本

powershell 复制代码
python topackage.py

双击MyWebViewApp.exe

下载体验

mp-779f4133-ea71-4a67-b4af-8cecfd13e8e1.cdn.bspapp.com/cloudstorag...

通过 pywebview(轻量级、使用系统原生 WebView 组件、Python 和 JavaScript 无缝交互),可以轻松创建桌面应用。本文详细介绍了从开发到打包的完整流程,提供了可直接使用的代码模板。无论是简单的工具类应用还是复杂的数据可视化项目,这个技术栈都能提供高效可靠的解决方案。

相关推荐
智购科技自动售货机厂家22 分钟前
2026自动售货机AI视觉识别优化:从YOLOv11n模型量化到RKNN部署的端侧推理工程实践~YH
javascript·人工智能·yolo·机器学习·计算机视觉·目标跟踪·perl
计算机魔术师23 分钟前
AI为拿高分不惜入侵网站:22个模型作弊审计,真相让人背脊发凉
前端
晓说前端25 分钟前
TypeScript 核心语法应用 —— Vue 3 中的使用(下)
前端·javascript·typescript·类型系统
qq_5137280434 分钟前
StaleElementReferenceException(陈旧元素引用异常)
python
zhangminghuan35 分钟前
微信小程序开发核心知识点全景解析(前端必备硬核基础)
前端·微信小程序·小程序
千里码aicood39 分钟前
基于Python的电商数据采集系统(大数据+爬虫)
开发语言·python
boooooooom1 小时前
尝尝咸淡:从朴素 RAG 到 Graph RAG——一个烹饪问答系统的三层检索升级之路
前端·后端·llm
cindershade1 小时前
让每条前端异常都能回答:该由谁修、为什么现在修
前端
战略性的菠萝1 小时前
研究生基础-Python快速入门(终)——面向对象
python
陈皮波比茶1 小时前
Python项目实战-网络机器人(爬虫)
开发语言·网络·爬虫·python·机器人