最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python的pywebview庫結(jié)合Flask和waitress開發(fā)桌面應(yīng)用程序完整代碼

 更新時(shí)間:2025年07月24日 12:01:34   作者:czliutz  
pywebview是輕量級(jí)Python庫,用于創(chuàng)建跨平臺(tái)桌面應(yīng)用,結(jié)合HTML/CSS/JS界面與Python交互,支持Windows/macOS/Linux,資源占用低,可與Flask、Waitress集成,便于開發(fā)、部署,本文給大家介紹python的pywebview庫結(jié)合Flask和waitress開發(fā)桌面應(yīng)用程序簡(jiǎn)介,感興趣的朋友一起看看吧

pywebview的用途與特點(diǎn)

用途
pywebview是一個(gè)輕量級(jí)Python庫,用于創(chuàng)建桌面應(yīng)用程序(GUI)。它通過嵌入Web瀏覽器組件(如Windows的Edge/IE、macOS的WebKit、Linux的GTK WebKit),允許開發(fā)者使用HTML/CSS/JavaScript構(gòu)建界面,并用Python處理后端邏輯。這種方式結(jié)合了Web技術(shù)的靈活性和Python的強(qiáng)大功能,適合快速開發(fā)跨平臺(tái)桌面應(yīng)用。

特點(diǎn)

  1. 跨平臺(tái)支持:原生支持Windows、macOS、Linux,無需額外配置。
  2. 輕量級(jí):無需完整的瀏覽器,僅依賴系統(tǒng)內(nèi)置Web組件。
  3. 雙向通信:HTML前端與Python后端可互相調(diào)用函數(shù)。
  4. 簡(jiǎn)單易用:API簡(jiǎn)潔,學(xué)習(xí)成本低。
  5. 資源占用少:相比Electron等框架,內(nèi)存占用更小。

基本使用方法

1. 安裝

pip install pywebview

2. 簡(jiǎn)單示例(Python與HTML交互)

import webview
def print_message(message):
    print(f"收到前端消息: {message}")
# 創(chuàng)建一個(gè)HTML字符串作為界面
html = """
<!DOCTYPE html>
<html>
<head>
    <title>PyWebView示例</title>
</head>
<body>
    <button onclick="python.print_message('你好,Python!')">發(fā)送消息到Python</button>
    <script>
        // 調(diào)用Python函數(shù)
        window.python = pywebview.api;
    </script>
</body>
</html>
"""
# 創(chuàng)建窗口并加載HTML
window = webview.create_window("PyWebView應(yīng)用", html=html)
webview.start(gui=None, debug=True)  # gui=None自動(dòng)選擇系統(tǒng)默認(rèn)瀏覽器引擎

結(jié)合Flask與waitress開發(fā)應(yīng)用

架構(gòu)設(shè)計(jì)

  • Flask:提供Web API,處理業(yè)務(wù)邏輯。
  • pywebview:作為桌面應(yīng)用的外殼,加載Flask的Web界面。
  • waitress:在生產(chǎn)環(huán)境中替代Flask內(nèi)置服務(wù)器,提供更好的性能。

開發(fā)環(huán)境代碼示例

# app.py - Flask后端
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/')
def index():
    return """
    <!DOCTYPE html>
    <html>
    <head>
        <title>Flask + PyWebView應(yīng)用</title>
    </head>
    <body>
        <h1>Hello from Flask!</h1>
        <button onclick="fetchData()">獲取數(shù)據(jù)</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后端的數(shù)據(jù)!"})
if __name__ == '__main__':
    # 開發(fā)環(huán)境:使用Flask內(nèi)置服務(wù)器
    app.run(debug=True, port=5000)
# desktop.py - PyWebView桌面應(yīng)用包裝
import webview
import threading
import subprocess
def run_flask():
    # 啟動(dòng)Flask應(yīng)用(開發(fā)環(huán)境)
    subprocess.run(['python', 'app.py'])
if __name__ == '__main__':
    # 在后臺(tái)線程中啟動(dòng)Flask
    flask_thread = threading.Thread(target=run_flask, daemon=True)
    flask_thread.start()
    # 創(chuàng)建PyWebView窗口,加載Flask應(yīng)用
    window = webview.create_window("桌面應(yīng)用", "http://localhost:5000")
    webview.start(gui=None, debug=True)

生產(chǎn)環(huán)境配置(使用waitress)

1. 修改Flask應(yīng)用(app.py)

# app.py - Flask后端(生產(chǎn)環(huán)境)
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/')
def index():
    return """
    <!-- 同上,HTML內(nèi)容 -->
    """
@app.route('/api/data')
def get_data():
    return jsonify({"message": "這是來自Flask后端的數(shù)據(jù)!"})
# 移除開發(fā)環(huán)境的app.run(),改為導(dǎo)出app實(shí)例

2. 使用waitress啟動(dòng)Flask

# server.py - 使用waitress啟動(dòng)Flask(生產(chǎn)環(huán)境)
from waitress import serve
from app import app
if __name__ == '__main__':
    serve(app, host='127.0.0.1', port=5000, threads=8)  # 生產(chǎn)環(huán)境使用waitress

3. 修改PyWebView應(yīng)用(desktop.py)

# desktop.py - PyWebView桌面應(yīng)用(生產(chǎn)環(huán)境)
import webview
import threading
import subprocess
def run_flask():
    # 啟動(dòng)Flask應(yīng)用(生產(chǎn)環(huán)境使用waitress)
    subprocess.run(['python', 'server.py'])
if __name__ == '__main__':
    # 在后臺(tái)線程中啟動(dòng)Flask
    flask_thread = threading.Thread(target=run_flask, daemon=True)
    flask_thread.start()
    # 創(chuàng)建PyWebView窗口,加載Flask應(yīng)用
    window = webview.create_window("桌面應(yīng)用", "http://localhost:5000")
    webview.start(gui=None, debug=False)  # 生產(chǎn)環(huán)境關(guān)閉調(diào)試模式

打包應(yīng)用的建議

為了將應(yīng)用分發(fā)給最終用戶,可以使用PyInstallercx_Freeze將Python代碼打包成單個(gè)可執(zhí)行文件:

# 使用PyInstaller打包
pyinstaller --onefile --windowed desktop.py

注意事項(xiàng)

  • 打包時(shí)需確保包含所有依賴項(xiàng)(如Flask、waitress、pywebview)。
  • 在macOS/Linux上可能需要額外配置以確保WebView組件正確加載。

總結(jié)

通過結(jié)合pywebview、Flaskwaitress,可以開發(fā)出兼具美觀界面和強(qiáng)大功能的跨平臺(tái)桌面應(yīng)用:

  • 開發(fā)階段:使用Flask內(nèi)置服務(wù)器和調(diào)試模式,提高開發(fā)效率。
  • 生產(chǎn)階段:使用waitress替代Flask服務(wù)器,提升性能和穩(wěn)定性。
  • 部署階段:使用PyInstaller打包為獨(dú)立可執(zhí)行文件,方便分發(fā)。

完整代碼

以下是在Windows平臺(tái)上結(jié)合PyWebView、Flask和Waitress的完整代碼實(shí)現(xiàn)。代碼分為三個(gè)主要文件,分別負(fù)責(zé)Flask后端、桌面應(yīng)用包裝和生產(chǎn)環(huán)境啟動(dòng)。

1. Flask后端代碼(app.py)

# app.py - Flask后端應(yīng)用
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應(yīng)用</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桌面應(yīng)用</h1>
            <p>這是一個(gè)基于Web技術(shù)的跨平臺(tái)桌面應(yīng)用示例。</p>
            <button onclick="fetchData()">獲取數(shù)據(jù)</button>
            <button onclick="callPythonFunction()">調(diào)用Python函數(shù)</button>
            <div id="result">點(diǎn)擊按鈕查看結(jié)果...</div>
            <script>
                // 從Python后端獲取數(shù)據(jù)
                async function fetchData() {
                    try {
                        const response = await fetch('/api/data');
                        if (!response.ok) throw new Error('網(wǎng)絡(luò)響應(yīng)失敗');
                        const data = await response.json();
                        document.getElementById('result').textContent = data.message;
                    } catch (error) {
                        document.getElementById('result').textContent = '錯(cuò)誤: ' + error.message;
                    }
                }
                // 調(diào)用Python函數(shù)(通過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計(jì)算結(jié)果: 5 × 3 = ${result}`;
                        } else {
                            document.getElementById('result').textContent = 'PyWebView API未加載';
                        }
                    } catch (error) {
                        document.getElementById('result').textContent = '調(diào)用Python函數(shù)時(shí)出錯(cuò): ' + error.message;
                    }
                }
            </script>
        </div>
    </body>
    </html>
    """)
# API路由 - 返回JSON數(shù)據(jù)
@app.route('/api/data')
def get_data():
    return jsonify({
        "message": "這是來自Flask后端的數(shù)據(jù)!",
        "timestamp": str(os.times()),
        "platform": "Windows桌面應(yīng)用"
    })
# 導(dǎo)出Flask應(yīng)用實(shí)例供其他模塊使用
if __name__ == '__main__':
    # 僅在直接運(yùn)行此文件時(shí)使用Flask內(nèi)置服務(wù)器(開發(fā)環(huán)境)
    app.run(debug=True, port=5000)

2. 開發(fā)環(huán)境啟動(dòng)腳本(desktop_dev.py)

# desktop_dev.py - 開發(fā)環(huán)境下的桌面應(yīng)用啟動(dòng)腳本
import webview
import threading
import subprocess
import time
import sys
from flask import Flask
def run_flask():
    """在子進(jìn)程中啟動(dòng)Flask開發(fā)服務(wù)器"""
    # 確定Python可執(zhí)行文件路徑
    python_exe = sys.executable
    # 啟動(dòng)Flask應(yīng)用
    server = subprocess.Popen(
        [python_exe, 'app.py'],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        universal_newlines=True
    )
    # 等待服務(wù)器啟動(dòng)
    for line in server.stdout:
        print(line.strip())
        if 'Running on' in line:
            break
    return server
class Api:
    """供前端JavaScript調(diào)用的Python API"""
    def multiply_numbers(self, a, b):
        """示例函數(shù):計(jì)算兩個(gè)數(shù)的乘積"""
        return a * b
if __name__ == '__main__':
    # 啟動(dòng)Flask服務(wù)器
    flask_server = run_flask()
    try:
        # 創(chuàng)建API實(shí)例
        api = Api()
        # 創(chuàng)建PyWebView窗口
        window = webview.create_window(
            title="PyWebView桌面應(yīng)用",
            url="http://localhost:5000",
            width=800,
            height=600,
            resizable=True,
            fullscreen=False,
            js_api=api  # 暴露Python API給JavaScript
        )
        # 啟動(dòng)PyWebView主循環(huán)
        webview.start(debug=True)
    finally:
        # 關(guān)閉Flask服務(wù)器
        if flask_server:
            flask_server.terminate()
            flask_server.wait()
            print("Flask服務(wù)器已關(guān)閉")

3. 生產(chǎn)環(huán)境啟動(dòng)腳本(desktop_prod.py)

# desktop_prod.py - 生產(chǎn)環(huán)境下的桌面應(yīng)用啟動(dòng)腳本
import webview
import threading
import subprocess
import time
import sys
from waitress import serve
from app import app
class Api:
    """供前端JavaScript調(diào)用的Python API"""
    def multiply_numbers(self, a, b):
        """示例函數(shù):計(jì)算兩個(gè)數(shù)的乘積"""
        return a * b
def run_waitress():
    """使用waitress啟動(dòng)Flask應(yīng)用(生產(chǎn)環(huán)境)"""
    print("正在啟動(dòng)Waitress服務(wù)器...")
    serve(app, host='127.0.0.1', port=5000, threads=8)
if __name__ == '__main__':
    # 在后臺(tái)線程中啟動(dòng)waitress服務(wù)器
    server_thread = threading.Thread(target=run_waitress, daemon=True)
    server_thread.start()
    # 等待服務(wù)器啟動(dòng)(給服務(wù)器一些時(shí)間初始化)
    print("等待服務(wù)器啟動(dòng)...")
    time.sleep(2)
    try:
        # 創(chuàng)建API實(shí)例
        api = Api()
        # 創(chuàng)建PyWebView窗口
        window = webview.create_window(
            title="PyWebView桌面應(yīng)用",
            url="http://localhost:5000",
            width=800,
            height=600,
            resizable=True,
            fullscreen=False,
            js_api=api  # 暴露Python API給JavaScript
        )
        # 啟動(dòng)PyWebView主循環(huán)(關(guān)閉調(diào)試模式)
        webview.start(debug=False)
    except Exception as e:
        print(f"應(yīng)用啟動(dòng)失敗: {e}")
    finally:
        print("應(yīng)用已關(guān)閉")

4. 運(yùn)行說明

開發(fā)環(huán)境

  1. 安裝依賴:

    pip install flask pywebview waitress
  2. 運(yùn)行開發(fā)環(huán)境腳本:

    python desktop_dev.py
    • 會(huì)自動(dòng)啟動(dòng)Flask開發(fā)服務(wù)器和PyWebView窗口。
    • 修改代碼后刷新頁面即可看到變化。

生產(chǎn)環(huán)境

  1. 打包應(yīng)用(可選):

    pyinstaller --onefile --windowed desktop_prod.py
  2. 直接運(yùn)行生產(chǎn)環(huán)境腳本:

    python desktop_prod.py
    • 使用waitress服務(wù)器替代Flask內(nèi)置服務(wù)器,性能更好。
    • 關(guān)閉了調(diào)試模式,更安全穩(wěn)定。

功能說明

  • 前后端交互

    • 前端通過fetch調(diào)用Flask API(如/api/data)。
    • 前端通過window.pywebview.api調(diào)用Python函數(shù)(如multiply_numbers)。
  • 界面特點(diǎn)

    • 使用Tailwind CSS風(fēng)格的界面(內(nèi)聯(lián)樣式確保打包時(shí)不丟失)。
    • 支持中文顯示(使用Microsoft YaHei字體)。
    • 響應(yīng)式設(shè)計(jì),適配不同屏幕尺寸。

這個(gè)實(shí)現(xiàn)可以作為Windows桌面應(yīng)用的基礎(chǔ)框架,你可以根據(jù)需要擴(kuò)展Flask API或修改前端界面。

另一個(gè)應(yīng)用示例代碼

# 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 構(gòu)建的桌面應(yīng)用!</h1>
        <a  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 應(yīng)用', 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()

到此這篇關(guān)于python的pywebview庫結(jié)合Flask和waitress開發(fā)桌面應(yīng)用程序完整代碼的文章就介紹到這了,更多相關(guān)python pywebview桌面應(yīng)用程序內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python中正反斜杠的正確使用方法

    Python中正反斜杠的正確使用方法

    在Python編程中,字符串是一個(gè)常用的數(shù)據(jù)類型,字符串中的斜杠(反斜杠\和正斜杠/)具有特殊的用法和意義,本文將介紹這兩種斜杠的用法,,需要的朋友可以參考下
    2025-04-04
  • python使用Pillow創(chuàng)建可自定義的圖標(biāo)生成器

    python使用Pillow創(chuàng)建可自定義的圖標(biāo)生成器

    在本篇博客中,我們將探討如何使用?wxPython?和?Pillow?庫創(chuàng)建一個(gè)簡(jiǎn)單的圖標(biāo)生成器,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-11-11
  • python爬取網(wǎng)頁版QQ空間,生成各類圖表

    python爬取網(wǎng)頁版QQ空間,生成各類圖表

    最近python課程學(xué)完了,琢磨著用python點(diǎn)什么東西,經(jīng)過一番搜索,盯上了QQ空間,本文主要講述了如何爬取網(wǎng)頁版QQ空間,并生成詞云圖、柱狀圖、折線圖、餅圖的各種示例代碼
    2021-06-06
  • Matplotlib 折線圖plot()所有用法詳解

    Matplotlib 折線圖plot()所有用法詳解

    這篇文章主要介紹了Matplotlib 折線圖plot()所有用法詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • 使用Python高效實(shí)現(xiàn)MySQL數(shù)據(jù)同步的幾種方案

    使用Python高效實(shí)現(xiàn)MySQL數(shù)據(jù)同步的幾種方案

    在數(shù)據(jù)驅(qū)動(dòng)的現(xiàn)代應(yīng)用中,數(shù)據(jù)庫同步是確保數(shù)據(jù)一致性和可用性的關(guān)鍵環(huán)節(jié),MySQL作為最流行的開源關(guān)系型數(shù)據(jù)庫之一,其數(shù)據(jù)同步需求廣泛存在于主從復(fù)制、數(shù)據(jù)遷移、備份恢復(fù)等場(chǎng)景,本文將詳細(xì)介紹如何使用Python實(shí)現(xiàn)高效可靠的MySQL數(shù)據(jù)同步方案,需要的朋友可以參考下
    2025-10-10
  • 20個(gè)解決日常編程問題的Python代碼分享

    20個(gè)解決日常編程問題的Python代碼分享

    在這篇文章中,主要和大家分享了20個(gè)Python代碼片段,以幫助你應(yīng)對(duì)日常編程挑戰(zhàn)。文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟上小編一起了解一下
    2023-01-01
  • python逐行讀寫txt文件的實(shí)例講解

    python逐行讀寫txt文件的實(shí)例講解

    下面小編就為大家分享一篇python逐行讀寫txt文件的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-04-04
  • 基于DataFrame改變列類型的方法

    基于DataFrame改變列類型的方法

    今天小編就為大家分享一篇基于DataFrame改變列類型的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-07-07
  • Python3去除頭尾指定字符的函數(shù)strip()、lstrip()、rstrip()用法詳解

    Python3去除頭尾指定字符的函數(shù)strip()、lstrip()、rstrip()用法詳解

    這篇文章主要介紹了Python3去除頭尾指定字符的函數(shù)strip()、lstrip()、rstrip()用法詳解,需要的朋友可以參考下
    2021-04-04
  • python畫圖——實(shí)現(xiàn)在圖上標(biāo)注上具體數(shù)值的方法

    python畫圖——實(shí)現(xiàn)在圖上標(biāo)注上具體數(shù)值的方法

    今天小編就為大家分享一篇python畫圖——實(shí)現(xiàn)在圖上標(biāo)注上具體數(shù)值的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07

最新評(píng)論

宁都县| 车致| 临西县| 化德县| 宾阳县| 太湖县| 仁怀市| 修武县| 九龙城区| 永新县| 时尚| 秦皇岛市| 黑龙江省| 中阳县| 铜陵市| 内黄县| 章丘市| 金川县| 仪陇县| 曲水县| 永胜县| 沾益县| 雷州市| 平和县| 临猗县| 和静县| 宜宾市| 龙山县| 界首市| 图木舒克市| 莱阳市| 前郭尔| 神木县| 洪湖市| 博野县| 扶沟县| 延庆县| 汉川市| 普洱| 台山市| 历史|