7人参与 • 2025-07-24 • Python
用途pywebview
是一个轻量级python库,用于创建桌面应用程序(gui)。它通过嵌入web浏览器组件(如windows的edge/ie、macos的webkit、linux的gtk webkit),允许开发者使用html/css/javascript构建界面,并用python处理后端逻辑。这种方式结合了web技术的灵活性和python的强大功能,适合快速开发跨平台桌面应用。
特点
pip install pywebview
import webview def print_message(message): print(f"收到前端消息: {message}") # 创建一个html字符串作为界面 html = """ <!doctype html> <html> <head> <title>pywebview示例</title> </head> <body> <button onclick="python.print_message('你好,python!')">发送消息到python</button> <script> // 调用python函数 window.python = pywebview.api; </script> </body> </html> """ # 创建窗口并加载html window = webview.create_window("pywebview应用", html=html) webview.start(gui=none, debug=true) # gui=none自动选择系统默认浏览器引擎
# app.py - flask后端 from flask import flask, jsonify app = flask(__name__) @app.route('/') def index(): return """ <!doctype html> <html> <head> <title>flask + pywebview应用</title> </head> <body> <h1>hello from flask!</h1> <button onclick="fetchdata()">获取数据</button> <div id="result"></div> <script> async function fetchdata() { const response = await fetch('/api/data'); const data = await response.json(); document.getelementbyid('result').textcontent = data.message; } </script> </body> </html> """ @app.route('/api/data') def get_data(): return jsonify({"message": "这是来自flask后端的数据!"}) if __name__ == '__main__': # 开发环境:使用flask内置服务器 app.run(debug=true, port=5000)
# desktop.py - pywebview桌面应用包装 import webview import threading import subprocess def run_flask(): # 启动flask应用(开发环境) subprocess.run(['python', 'app.py']) if __name__ == '__main__': # 在后台线程中启动flask flask_thread = threading.thread(target=run_flask, daemon=true) flask_thread.start() # 创建pywebview窗口,加载flask应用 window = webview.create_window("桌面应用", "http://localhost:5000") webview.start(gui=none, debug=true)
# app.py - flask后端(生产环境) from flask import flask, jsonify app = flask(__name__) @app.route('/') def index(): return """ <!-- 同上,html内容 --> """ @app.route('/api/data') def get_data(): return jsonify({"message": "这是来自flask后端的数据!"}) # 移除开发环境的app.run(),改为导出app实例
# server.py - 使用waitress启动flask(生产环境) from waitress import serve from app import app if __name__ == '__main__': serve(app, host='127.0.0.1', port=5000, threads=8) # 生产环境使用waitress
# desktop.py - pywebview桌面应用(生产环境) import webview import threading import subprocess def run_flask(): # 启动flask应用(生产环境使用waitress) subprocess.run(['python', 'server.py']) if __name__ == '__main__': # 在后台线程中启动flask flask_thread = threading.thread(target=run_flask, daemon=true) flask_thread.start() # 创建pywebview窗口,加载flask应用 window = webview.create_window("桌面应用", "http://localhost:5000") webview.start(gui=none, debug=false) # 生产环境关闭调试模式
为了将应用分发给最终用户,可以使用pyinstaller
或cx_freeze
将python代码打包成单个可执行文件:
# 使用pyinstaller打包 pyinstaller --onefile --windowed desktop.py
注意事项:
通过结合pywebview
、flask
和waitress
,可以开发出兼具美观界面和强大功能的跨平台桌面应用:
以下是在windows平台上结合pywebview、flask和waitress的完整代码实现。代码分为三个主要文件,分别负责flask后端、桌面应用包装和生产环境启动。
# app.py - flask后端应用 from flask import flask, jsonify, render_template_string import os app = flask(__name__) # 确保中文正常显示 app.config['json_as_ascii'] = false # 首页路由 @app.route('/') def index(): return render_template_string(""" <!doctype html> <html lang="zh-cn"> <head> <meta charset="utf-8"> <title>pywebview + flask应用</title> <style> body { font-family: 'microsoft yahei', sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; } .container { background-color: #f9f9f9; border-radius: 8px; padding: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); } h1 { color: #333; } button { background-color: #4caf50; color: white; border: none; padding: 10px 20px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; border-radius: 4px; } #result { margin-top: 20px; padding: 10px; background-color: #e8f5e9; border-radius: 4px; } </style> </head> <body> <div class="container"> <h1>pywebview + flask桌面应用</h1> <p>这是一个基于web技术的跨平台桌面应用示例。</p> <button onclick="fetchdata()">获取数据</button> <button onclick="callpythonfunction()">调用python函数</button> <div id="result">点击按钮查看结果...</div> <script> // 从python后端获取数据 async function fetchdata() { try { const response = await fetch('/api/data'); if (!response.ok) throw new error('网络响应失败'); const data = await response.json(); document.getelementbyid('result').textcontent = data.message; } catch (error) { document.getelementbyid('result').textcontent = '错误: ' + error.message; } } // 调用python函数(通过pywebview的api) async function callpythonfunction() { try { // 确保pywebview api已加载 if (window.pywebview && window.pywebview.api) { const result = await window.pywebview.api.multiply_numbers(5, 3); document.getelementbyid('result').textcontent = `python计算结果: 5 × 3 = ${result}`; } else { document.getelementbyid('result').textcontent = 'pywebview api未加载'; } } catch (error) { document.getelementbyid('result').textcontent = '调用python函数时出错: ' + error.message; } } </script> </div> </body> </html> """) # api路由 - 返回json数据 @app.route('/api/data') def get_data(): return jsonify({ "message": "这是来自flask后端的数据!", "timestamp": str(os.times()), "platform": "windows桌面应用" }) # 导出flask应用实例供其他模块使用 if __name__ == '__main__': # 仅在直接运行此文件时使用flask内置服务器(开发环境) app.run(debug=true, port=5000)
# desktop_dev.py - 开发环境下的桌面应用启动脚本 import webview import threading import subprocess import time import sys from flask import flask def run_flask(): """在子进程中启动flask开发服务器""" # 确定python可执行文件路径 python_exe = sys.executable # 启动flask应用 server = subprocess.popen( [python_exe, 'app.py'], stdout=subprocess.pipe, stderr=subprocess.stdout, universal_newlines=true ) # 等待服务器启动 for line in server.stdout: print(line.strip()) if 'running on' in line: break return server class api: """供前端javascript调用的python api""" def multiply_numbers(self, a, b): """示例函数:计算两个数的乘积""" return a * b if __name__ == '__main__': # 启动flask服务器 flask_server = run_flask() try: # 创建api实例 api = api() # 创建pywebview窗口 window = webview.create_window( title="pywebview桌面应用", url="http://localhost:5000", width=800, height=600, resizable=true, fullscreen=false, js_api=api # 暴露python api给javascript ) # 启动pywebview主循环 webview.start(debug=true) finally: # 关闭flask服务器 if flask_server: flask_server.terminate() flask_server.wait() print("flask服务器已关闭")
# desktop_prod.py - 生产环境下的桌面应用启动脚本 import webview import threading import subprocess import time import sys from waitress import serve from app import app class api: """供前端javascript调用的python api""" def multiply_numbers(self, a, b): """示例函数:计算两个数的乘积""" return a * b def run_waitress(): """使用waitress启动flask应用(生产环境)""" print("正在启动waitress服务器...") serve(app, host='127.0.0.1', port=5000, threads=8) if __name__ == '__main__': # 在后台线程中启动waitress服务器 server_thread = threading.thread(target=run_waitress, daemon=true) server_thread.start() # 等待服务器启动(给服务器一些时间初始化) print("等待服务器启动...") time.sleep(2) try: # 创建api实例 api = api() # 创建pywebview窗口 window = webview.create_window( title="pywebview桌面应用", url="http://localhost:5000", width=800, height=600, resizable=true, fullscreen=false, js_api=api # 暴露python api给javascript ) # 启动pywebview主循环(关闭调试模式) webview.start(debug=false) except exception as e: print(f"应用启动失败: {e}") finally: print("应用已关闭")
安装依赖:
pip install flask pywebview waitress
运行开发环境脚本:
python desktop_dev.py
打包应用(可选):
pyinstaller --onefile --windowed desktop_prod.py
直接运行生产环境脚本:
python desktop_prod.py
前后端交互:
fetch
调用flask api(如/api/data
)。window.pywebview.api
调用python函数(如multiply_numbers
)。界面特点:
microsoft yahei
字体)。这个实现可以作为windows桌面应用的基础框架,你可以根据需要扩展flask api或修改前端界面。
# create desktop app by pywebview """ replace the flask module with waitress module. to avoid the warning: warning: this is a development server. do not use it in a production deployment. use a production wsgi server instead. """ import webview from flask import flask, render_template_string import threading from waitress import serve # create a flask application app = flask(__name__) # define the route @app.route('/') def index(): return render_template_string(""" <!doctype html> <html lang="zh"> <head> <meta charset="utf-8"> <title>pywebview + flask 示例</title> </head> <body> <h1>欢迎使用 pywebview 和 flask 构建的桌面应用!</h1> <a href="http://cnliutz.ipyingshe.net" rel="external nofollow" >blog site</a> </body> </html> """) def create_webview(): # define the url of the flask application to load url = "http://127.0.0.1:5000" # create a window and load the specified url window = webview.create_window('pywebview + flask 应用', url) # run the application webview.start() if __name__ == '__main__': # start the waitress server in a separate thread def run_waitress(): try: # start waitress to run the flask application serve(app, host='127.0.0.1', port=5000) except exception as e: print(f"error starting waitress: {e}") waitress_thread = threading.thread(target=run_waitress) waitress_thread.daemon = true waitress_thread.start() # start pywebview create_webview()
到此这篇关于python的pywebview库结合flask和waitress开发桌面应用程序完整代码的文章就介绍到这了,更多相关python pywebview桌面应用程序内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论