我正在尝试学习使用 Python eel 库。具体来说,我试图通过单击按钮(运行 JavaScript 函数)来调用 Python 函数。
在我的文件夹中有四个文件,排列如下:
|
+--- main.py
|
+--- web-gui
|
+--- index.html
|
+--- main.js
|
+--- style.css
这是我的main.py:
# Start GUI using eel
import eel
eel.init('web-gui')
eel.start('index.html', size=(1440, 900), block=False)
# Boolean data from javascript (true or false) is given to python
result = eel.js_startPython()()
print('Javascript says hello! Your result is', bool(result))
这是我的main.js:
// Javascript passes data to Python when button is pushed
document.getElementById("data").addEventListener("click", js_startPython);
eel.expose(js_startPython); // Expose this function to Python
function js_startPython() {
console.log('successful button click')
return result = true;
}
这是我的index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Python Decider</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<div class="text">
<h1>
The Python Decider
</h1>
<p>
Have a yes/no question? Click on the button to find out your answer.
</p>
</div>
<div class="button">
<div class="flex align-midde align-center">
<a class="button glow-button" href="#" id="data">Click me!</a>
</div>
</div>
</div>
<script type="text/javascript" src="/eel.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
我希望,当我按下按钮时,python 控制台将返回:
>>> Javascript says hello! Your result is True
我当前的问题是 JavaScript 代码在未被调用的情况下运行。不按任何东西,它显示
>>> Javascript says hello! Your result is True # before button is even pressed
很抱歉这篇文章很长。我感谢任何答案。如果这个问题已经在 SO 上被问到,我也很抱歉,但我很确定它还没有被问到。
相关分类