Repository navigation
Expand file tree
/
Copy pathbind_inline.py
More file actions
76 lines (61 loc) · 1.99 KB
/
Copy pathbind_inline.py
File metadata and controls
76 lines (61 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import os
from urllib.parse import quote
from webview import Webview, SizeHint, Size
# # Create HTML with JavaScript that calls Python functions
html = """
<html lang="zh">
<head>
<title>Python-JavaScript Binding Demo</title>
<script>
// 定义所有的 JavaScript 函数
async function callPython() {
try {
const result = await hello();
document.getElementById('result').innerHTML = result;
} catch (err) {
console.error('Error calling Python:', err);
}
}
async function callPythonWithArgs() {
try {
const result = await add(40, 2);
document.getElementById('result').innerHTML = `Result: ${result}`;
} catch (err) {
console.error('Error calling Python:', err);
}
}
function updateFromPython(message) {
document.getElementById('result').innerHTML = `Python says: ${message}`;
}
</script>
</head>
<body>
<h1>Python-JavaScript Binding Demo</h1>
<button onclick="callPython()">Call Python</button>
<button onclick="callPythonWithArgs()">Call Python with Args</button>
<div id="result"></div>
</body>
</html>
"""
# Create webview instance
webview = Webview(debug=True)
# Define Python functions to be called from JavaScript
def hello():
# Call JavaScript from Python
webview.eval("updateFromPython('Hello from Python!')")
return "Hello from Python!"
def add(a, b):
result = a + b
return result
# Bind Python functions
webview.bind("hello", hello)
webview.bind("add", add)
webview.title = "Python-JavaScript Binding Demo"
webview.size = Size(640, 480, SizeHint.FIXED)
# Get the absolute path to the HTML file
current_dir = os.path.dirname(os.path.abspath(__file__))
html_path = os.path.join(current_dir, 'local_use_bind.html')
# Load the inline HTML
webview.navigate(f"data:text/html,{quote(html)}")
# Run the webview
webview.run()