Flask + PyInstaller = 客户端

582 阅读1分钟

Flask + PyInstaller = 客户端

有些特殊情况需要开发客户端,Python有几个常用的几个GUI框架,如 PyQt、wxPython等

但使用这些GUI框架往往界面比较丑,而且GUI的线程问题处理起来比较麻烦,界面主线程无法回调,做个倒计时之类的东西都麻烦

不如直接前后端分离,使用flask做客户端的服务,html写页面,使用pyinstaller打包成exe,这样可以在任何windows电脑点击exe打开使用

安装依赖

pip install flask pyinstaller

文件结构

  • root
    • templates
      • hello.html
    • application.py

代码

application.py

import webbrowser
from flask import Flask, render_template

app = Flask(__name__)


@app.route("/")
def hello_world():
    return render_template('hello.html')


if __name__ == '__main__':
    webbrowser.open('http://localhost:15000')
    app.run(host='localhost', port=15000)

templates/hello.html

<!doctype html>
<html>

<head>
    <title>演示客户端</title>
</head>

<body>
    <h1>演示</h1>
    <p>演示如何使用Flask + PyInstaller制作客户端</p>
</body>

</html>

打包

pyinstaller application.py --add-data=templates;templates --name=demo

执行后,将在项目目录下生产 dist/demo 目录,双击 dist/demo/demo.exe 即可打开客户端

  • 也可使用python调用pyinstaller,运行下面这段代码和上面的打包命令一样的效果
from PyInstaller.__main__ import run

if __name__ == '__main__':
    opts = ['application.py', '--add-data=templates;templates', '--name=demo']
    run(opts)