安装pywebview模块
python -m pip install pywebview -i https://pypi.tuna.tsinghua.edu.cn/simple/
编写python代码
import webview
import os
import json
class API:
def save_note(self,note):
with open('note.json','w') as f:
json.dump({'note':note},f)
return '保存成功'
def main():
api=API()
webview.create_window('记事本','1.html',js_api=api)
webview.start()
if __name__=='__main__':
main()
提供了一个save_note()方法,作用是将用户在文本框中输入的内容保存到文件中。
编写页面代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>记事本</title>
</head>
<body>
<h1>记事本</h1>
<textarea id="note" rows="10" cols="30"></textarea>
<button onclick="save()">保存</button>
<script>
function save() {
var note = document.getElementById("note").value;
window.pywebview.api.save_note(note).then(response => {
alert(response);
});
}
</script>
</script>
</body>
</html>
页面上有一个文本框和一个按钮,文本框让用户输入要保存到文件的内容,按钮调用上面的save_note()方法。
文件内容
{"note": "\u5e8a\u524d\u660e\u6708\u5149"}