pywebview 入门
文档地址
地址 https://pywebview.flowrl.com/guide/
一、pywebview 简介
1. 什么是 pywebview?
pywebview 是一个轻量级的 python 库,旨在简化桌面应用程序的开发。它利用系统的 WebView 组件,使得开发人员可以使用现代 Web 技术(HTML、CSS、JavaScript)来创建用户界面,同时使用 python 处理业务逻辑。pywebview 使得创建跨平台桌面应用程序变得更加简单和高效。
2. 主要功能和特点
-  
跨平台支持, pywebview 支持 Windows、macOS 和 Linux,确保应用程序可以在多个平台上运行。
 -  
简易集成,可以轻松地将 Web 应用嵌入到桌面应用中,无需复杂的设置
 -  
安全性:支持禁用本地文件访问和执行外部脚本,提供额外的安全层。
 
二、安装使用
1、安装
# 会默认安装基本的依赖 pip install pywebview
2、Mac系统,如果使用的是自己安装的python,需要安装安装下面依赖
pip install pyobjc
3、如果你希望使用 pySide2 作为 GUI 库来创建和管理窗口执行下面的命令
pip install pywebview[qt]
4、pywebview默认使用系统自带的 WebView 组件作为浏览器引擎
-  
windows 使用默认使用 Internet Explorer 11 作为 WebView 引擎。
 -  
macOS 默认使用 WebKit 引擎,这是 macOS 自带的 WebView 组件,基于 Safari 浏览器的引擎。
 -  
Linux 默认使用 WebKitGTK,这是 Linux 上常用的 WebView 组件,基于 WebKit 引擎
 
如果需要其他引擎,需要单独安装:
5、windows中使用 CEF(Chromium Embedded Framework)作为引擎
pip install cefpython3 
指定backend
import webview
webview.create_window('My App', 'https://www.baidu.com/', backend='cef')
webview.start()
 
三、使用示例
1、基础使用
# demo1.py
import webview
window = webview.create_window('Woah dude!', 'https://pywebview.flowrl.com')
webview.start() 
create_window函数用于创建一个新窗口,并返回一个 window 对象实例。在调用webview.start()之前创建的窗口将在 GUI 循环启动后立即显示。GUI 循环启动后创建的窗口也会立即显示。您可以创建任意数量的窗口,所有已打开的窗口都会按创建顺序存储在webview.windows列表中。
2、同时打开两个窗口
import webview
first_window = webview.create_window('Woah dude!', 'https://pywebview.flowrl.com')
second_window = webview.create_window('Second window', 'https://woot.fi')
webview.start() 
3、调用后台执行
webview.start会启动一个 GUI 循环,并阻止进一步的代码执行,直到最后一个窗口被销毁。由于 GUI 循环是阻塞的,您必须在单独的线程或进程中执行后台逻辑。您可以通过将函数传递给webview.start(func, (params,))来执行后台代码。这将启动一个单独的线程,与手动启动线程是相同的。
# 界面打开后就会自动弹窗
import webview
def custom_logic(window):
    window.toggle_fullscreen()
    window.evaluate_js('alert("Nice one brother")')
window = webview.create_window('Woah dude!', html='<h1>Woah dude!<h1>')
webview.start(custom_logic, window) 
window.evaluate_js可以使用python执行js代码
4、js调用python
import webview
# 这里是核心,是和js中交互的关键
class Api():
  def log(self, value):
    print(value)
   
webview.create_window("Test", html="<button οnclick='pywebview.api.log(\"Woah dude!\")'>Click me</button>", js_api=Api())
webview.start() 
在打开的界面中点击按钮,后台就可以看到log函数被调用,会把传入的值
Woah dude!打印到控制台
5、HTTP Server
pywebview 默认使用 bottlepy 作为http 服务,默认端口是8080,前后服务也可以使用http 通信
-  
index.html
 
<!DOCTYpE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>pywebview Example</title>
</head>
<body>
    <h1>pywebview AJAX Example</h1>
    <button οnclick="fetchData()">Fetch Data</button>
    <p id="response"></p>
    <script>
        function fetchData() {
            fetch('http://localhost:8080/api/data')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('response').innerText = data.message;
                })
                .catch(error => console.error('Error fetching data:', error));
        }
    </script>
</body>
</html>
 
-  
demo.py
 
import webview
from bottle import Bottle, run, static_file
import threading
app = Bottle()
@app.route("/api/data")
def get_data():
    return {"message": "Hello from the server!"}
@app.route("/")
def index():
    return static_file("index.html", root=".")
# 启动 HTTp 服务器
def start_server():
    run(app, host="localhost", port=8080)
if __name__ == "__main__":
    # 在单独的线程中启动 HTTp 服务器
    server_thread = threading.Thread(target=start_server)
    server_thread.daemon = True
    server_thread.start()
    # 创建并启动 pywebview 窗口
    webview.create_window("pywebview Example", "http://localhost:8080")
    webview.start()
 
6、使用其他web框架,比如Flask
-  
安装falsk
 
pip install flask
-  
项目结构
project/ ├── app.py ├── assets/ │ └── (your static files like CSS, JS, images, etc.) └── templates/ └── index.html -  
app.py
from flask import Flask, render_template import webview # Create the Flask app app = Flask(__name__, static_folder='./assets', template_folder='./templates') # Define a route for the main page @app.route('/') def index(): return render_template('index.html') # Create a Flask server and a pywebview window if __name__ == '__main__': # Create a pywebview window with the Flask server webview.create_window('Flask example', app) webview.start() -  
templates/index.html
<!DOCTYpE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Flask Example</title> </head> <body> <h1>Hello from Flask and pywebview!</h1> </body> </html> 
7、指向本地html文件
import webview
# this will be served as file:///home/pywebview/project/index.html
webview.create_window('Woah dude!', '/home/pywebview/project/index.html')
webview.start() 
8、直接渲染html字符
import webview
webview.create_window('Woah dude!', html='<h1>Woah dude!<h1>')
webview.start() 




















