學習一下pywebview,很方便的前後臺交互技術。
近日,Pywebview發佈了2.0的新版本。Pywebview允許您使用Web技術和Python相結合創建GUI應用程序。 使你可以用Python進行應用程序邏輯控制,使用Javascript和CSS生成GUI。 Pywebview對freeze支持良好從而實現了程序的可執行封裝。
Pywebview2.0中最大的變化是Python和Javascript之間的雙向通信,它完全消除了對Python Web服務器的需求。
import webview
from threading import Thread
class Api():
def helloWorld(self,param):
# 可執行業務邏輯
return 'return result'
def load_html():
webview.load_html("""
<style>
#hdl_id{
height:25%;
width:100%;
font-size: 30px;
background-color:skyblue;
}
</style>
<!-- 也可以引入css文件-->
<!-- <link rel="stylesheet" type="text/css" href="test.css"/> -->
<table style="border:1px solid #cccaca;background:red;">
<tr>
<td>11</td>
<td>12</td>
</tr>
<tr>
<td>21</td>
<td>22</td>
</tr>
</table>
<div id="hdl_id" οnclick="hdl_function_test()">enene</div>
<script>
function hdl_function_test(){
alert('be clicked!')
}
</script>
<!-- 也可以引入js文件-->
<!-- <script type="text/javascript" src="test.js"></script> -->
""")
# 新增的加載自定義CSS的load_css函數
# 按如下使用時 TypeError: evaluate_js() takes exactly 2 arguments (1 given)
# webview.load_css(stylesheet="""
# #hdl_id{
# height:25%;
# width:100%;
# font-size: 30px;
# background-color:skyblue;
# }
# """,uid="master")
#創建窗口
second_window = webview.create_window('second window')
#指定WebView並添加內容
webview.load_html("""
<span>this is a test</span><br>
<div style="background-color:grey;">gegegeg</div>
<input type="button" id="test" value="click it" οnclick="test()">
""",uid=second_window)
#回調後臺業務邏輯
webview.evaluate_js(script="""
pywebview.api.helloWorld().then(function(response){
alert(response)
})
""")
if __name__ == '__main__':
api = Api()
t = Thread(target=load_html)
t.start()
test = webview.create_window('first window', js_api=api)
pywebview 2.0 released
http://www.myegotraps.com/pywebview-2-0-released/
說明文檔
https://github.com/r0x0r/pywebview
執行結果: