赞
踩
本文介绍用python+html开发桌面应用程序,主要是用pywebview来加载、显示html页面。
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许可的开源项目。
python -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple/ pywebview
import webview
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>
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()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。