python+html开发桌面应用程序(一)pywebview介绍

本文介绍用python+html开发桌面应用程序,主要是用pywebview来加载、显示html页面。

一.pywebview简介

  • pywebview是围绕webview组件的轻型跨平台包装器,它允许在其自己的本机GUI窗口中显示HTML内容。您可能会想到Python的Electron,但是pywebview打包的执行文件小很多。

  • 它为您提供了桌面应用程序中的Web技术功能,隐藏了GUI基于浏览器的事实。您可以将pywebview与轻量级的Web框架(例如Flask或Bottle)一起使用,也可以单独使用python和DOM之间的双向桥梁。

  • pywebview使用本机GUI创建Web组件窗口:Windows上的WinForms,macOS上的Cocoa和Linux上的QT或GTK。
    如果选择冻结应用程序,则pywebview不会捆绑重型的GUI工具箱或Web渲染器,从而使可执行文件的大小保持较小。

  • pywebview是BSD许可的开源项目。

二.实例代码

  1. 安装pywebview
python -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple/ pywebview
  1. 引入pywebview
import webview
  1. 前端html代码
    在html页面中与python交互时,需要在script中增加
window.addEventListener('pywebviewready', function() {
        console.log('pywebview is ready');
    })

再通过pywebview.api来调用python里面的函数

pywebview.api.select_dir().then((response)=>{

        })

select_dir()是在python中定义的函数。完整前端代码如下:

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
</head>
<body>
<input id="select_dir_id" disabled="disabled" style="width: 400px" placeholder="显示选择的目录">
<button onClick="selectDir()">测试选择目录</button><br/>
<input id="select_file_id" disabled="disabled" style="width: 400px" placeholder="显示选择的文件(*.bmp;*.jpg;*.gif;*.png)">
<button onClick="selectFile()">测试选择文件</button><br/>
<input id="input1_id" placeholder="参数1">
<input id="input2_id" placeholder="参数2">
<input id="input3_id" placeholder="参数3">
<button onClick="testArgcs()">测试传入多参数,模拟耗时请求</button><br/>
<div id="response-container"></div>
<script>
    window.addEventListener('pywebviewready', function() {
        console.log('pywebview is ready');
    })

    function selectDir() {
        pywebview.api.select_dir().then((response)=>{
            //alert(response);
            document.getElementById('select_dir_id').value = response;
        })
    }
    
    function selectFile() {
        pywebview.api.select_file().then((response)=>{
            //alert(response);
            document.getElementById('select_file_id').value = response;
        })
    }
    function testArgcs() {
        var arg1 = document.getElementById('input1_id').value;
        var arg2 = document.getElementById('input2_id').value;
        var arg3 = document.getElementById('input3_id').value;
        pywebview.api.test_argcs(arg1, arg2, arg3).then((response)=>{
            alert(response);
        })
    }
</script>
</body>
</html>
  1. python代码
    与html交互需要定义一个类,再实例化一个类对象传给pywebview,这样html就能调用类里面的函数。代码如下
class Api:
    def select_dir(self):  # 选择目录
        result = window.create_file_dialog(webview.FOLDER_DIALOG)
        print(result)
        return result[0] if result else ''

    def select_file(self):  # 选择文件
        file_types = ('Image Files (*.bmp;*.jpg;*.gif;*.png)', 'All files (*.*)')
        result = window.create_file_dialog(webview.OPEN_DIALOG, allow_multiple=True, file_types=file_types)
        print(result)
        return result[0] if result else ''

    def test_argcs(self, arg1, arg2, arg3):  # 测试传入多参数,模拟耗时请求
        print(arg1, arg2, arg3)
        import time
        time.sleep(3)

        return '返回结果:{0},{1},{2}'.format(arg1, arg2, arg3)

创建并启动窗口

api = Api()
    window = webview.create_window('pywebview中html和python交互的例子', html=html, js_api=api)
    webview.start()

下一章介绍python+html开发桌面应用程序(二)pywebview+vue实现系统登录

  • 3
    点赞
  • 67
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
Electron 是一个基于 Node.js 和 Chromium 的桌面应用程序开发框架,可以使用 HTML、CSS 和 JavaScript 来构建跨平台的桌面应用程序。在本文中,我们将介绍如何使用 Python 和 Flask 结合 Electron 编写一个简单的桌面应用程序。 1. 安装 Electron 首先,我们需要安装 Electron。可以通过 npm 来安装它: ``` npm install electron --save-dev ``` 2. 创建 Electron 应用程序 接下来,我们需要创建一个基本的 Electron 应用程序。在项目根目录下创建一个名为 main.js 的文件,并添加以下代码: ``` const { app, BrowserWindow } = require('electron') const path = require('path') function createWindow() { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) win.loadFile('index.html') win.webContents.openDevTools() } app.whenReady().then(() => { createWindow() app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow() } }) }) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) ``` 这段代码创建了一个基本的窗口,加载了一个名为 index.html 的文件,并打开了开发者工具。 3. 创建 Flask 应用程序 然后,我们需要创建一个 Flask 应用程序。在项目根目录下创建一个名为 server.py 的文件,并添加以下代码: ``` from flask import Flask, jsonify app = Flask(__name__) @app.route('/api') def api(): return jsonify({'message': 'Hello, World!'}) if __name__ == '__main__': app.run(debug=True) ``` 这段代码创建了一个简单的 Flask 应用程序,具有一个名为 /api 的路由,返回了一个 JSON 响应。 4. 集成 Flask 应用程序 现在,我们需要将 Flask 应用程序集成到 Electron 应用程序中。在 main.js 文件中添加以下代码: ``` const { app, BrowserWindow } = require('electron') const path = require('path') const { spawn } = require('child_process') let flaskProcess = null const flaskPath = path.join(__dirname, 'server.py') function createWindow() { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }) win.loadFile('index.html') win.webContents.openDevTools() } app.whenReady().then(() => { flaskProcess = spawn('python', [flaskPath]) createWindow() app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow() } }) }) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) app.on('before-quit', () => { flaskProcess.kill() }) ``` 这段代码启动了一个 Python 进程来运行 Flask 应用程序,并在应用程序关闭之前杀死该进程。 5. 发起请求 最后,我们需要在渲染进程中发起请求。在项目根目录下创建一个名为 index.html 的文件,并添加以下代码: ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hello, World!</title> </head> <body> <h1 id="message"></h1> <script> const { ipcRenderer } = require('electron') ipcRenderer.on('message', (event, message) => { document.getElementById('message').textContent = message }) fetch('http://localhost:5000/api') .then(response => response.json()) .then(data => { ipcRenderer.send('message', data.message) }) .catch(error => console.error(error)) </script> </body> </html> ``` 这段代码使用 IPC 通信来从 Python 进程接收消息,并使用 fetch API 发起一个请求来获取 Flask 应用程序的响应。 6. 运行应用程序 现在,我们可以通过运行以下命令来启动应用程序: ``` npm start ``` 这将同时启动 Electron 应用程序和 Flask 应用程序,并打开一个窗口,显示来自 Flask 应用程序的消息。 至此,我们已经成功地构建了一个使用 Python、Flask 和 Electron 框架的桌面应用程序

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丁爸

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值