Python中如何将Web应用打包成桌面应用,类似pgadmin4的实现方式?

其实是想做一个桌面应用程序,但是不会写界面。所以界面想用 html/css/jquery 那一套来做,但是怎么实现呢?

我知道肯定是由这样的方案的。譬如 pgadmin4 的 windows 版本。
就是不知道它是如何实现的。。。
Python中如何将Web应用打包成桌面应用,类似pgadmin4的实现方式?

8 回复

Although developed using web technologies, pgAdmin 4 can be deployed either on
a web server using a browser, or standalone on a workstation. The runtime/
subdirectory contains a QT based runtime application intended to allow this -
it is essentially a browser and Python interpreter in one package which is
capable of hosting the Python application and presenting it to the user as a
desktop application.

自问自答。。。。
最终还是用的 QT 内嵌一个浏览器。。。


用 PyInstaller 打包 Web 应用为桌面应用,核心思路是:把 Flask/Django 等框架和前端资源打包进可执行文件,启动时运行本地服务器并用浏览器打开。下面是一个完整示例:

1. 项目结构

my_web_app/
├── app.py              # Flask 应用
├── static/             # 静态资源
├── templates/          # HTML 模板
└── build_exe.py        # 打包脚本

2. Flask 应用示例 (app.py)

from flask import Flask, render_template
import threading
import webbrowser

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html', message="Hello from Desktop!")

def open_browser():
    webbrowser.open('http://127.0.0.1:5000')

if __name__ == '__main__':
    threading.Timer(1.5, open_browser).start()
    app.run(debug=False, port=5000)

3. 打包脚本 (build_exe.py)

import PyInstaller.__main__
import os

# 收集静态文件路径
static_files = []
for root, dirs, files in os.walk('static'):
    for file in files:
        full_path = os.path.join(root, file)
        static_files.append(f'{full_path};static/{file}')

templates_files = []
for root, dirs, files in os.walk('templates'):
    for file in files:
        full_path = os.path.join(root, file)
        templates_files.append(f'{full_path};templates/{file}')

# 构建 PyInstaller 命令
args = [
    'app.py',
    '--name=MyWebApp',
    '--onefile',
    '--windowed',
    '--add-data=templates;templates',
    '--add-data=static;static',
    '--hidden-import=flask',
    '--hidden-import=jinja2',
    '--clean'
]

# 添加静态文件
for sf in static_files + templates_files:
    args.append(f'--add-data={sf}')

PyInstaller.__main__.run(args)

4. 运行打包

pip install flask pyinstaller
python build_exe.py

生成的 exe 在 dist/ 目录,双击即可运行桌面应用。

关键点说明:

  • --onefile 打包成单个可执行文件
  • --windowed 隐藏控制台窗口(Windows)
  • --add-data 将模板和静态文件嵌入可执行文件
  • 启动时自动打开浏览器访问本地服务

pgadmin4 也是类似原理,不过它用 QtWebEngine 做内嵌浏览器。如果要做原生窗口,可以考虑 pywebviewcefpython

总结建议:用 PyInstaller 打包 Web 应用时注意处理好静态资源路径。

electron



谢谢。

也推荐 electron,撸起来特别简单,扩展走 node.js 也很方便,可用性足够高了。

我六月才独自撸出了一整套前后的进销存+pos,pos client 的部分就用的这个,走 RS232 接秤子(进货)跟打印。还不够的自己从 node.js 下手也不是什么大事。

顺带抱怨一下 pgadmin4 真特么比 3 难用得多,而且 ui 实在是…

nwjs 也是可以得 https://www.v2ex.com/t/381573#reply0
electron 也行,只需要会前端就能搞了

回到顶部