[英]Can't access javascript function from python through eel
我一直在尝试通过他们的文档学习 Eel 的基础知识。 我努力学习如何通过 python 触发 javascript function,所以我尝试直接从他们的 github 下载他们的 Hello World 示例。您可以在此处打开它。
但我仍然得到同样的错误,即:发生异常:AttributeError 模块 'eel' 没有属性 'say_hello_js'
代码如下:(也可以在上面的链接github上查)
你好.py
import eel
# Set web files folder
eel.init('web')
@eel.expose # Expose this function to Javascript
def say_hello_py(x):
print('Hello from %s' % x)
say_hello_py('Python World!')
eel.say_hello_js('Python World!') # Call a Javascript function
eel.start('hello.html', size=(300, 200)) # Start
网站/index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello, World!</title>
<!-- Include eel.js - note this file doesn't exist in the 'web' directory -->
<script type="text/javascript" src="/eel.js"></script>
<script type="text/javascript">
eel.expose(say_hello_js); // Expose this function to Python
function say_hello_js(x) {
console.log("Hello from " + x);
}
say_hello_js("Javascript World!");
eel.say_hello_py("Javascript World!"); // Call a Python function
</script>
</head>
<body>
Hello, World!
</body>
</html>
会不会是我python或者Eel的版本错误? 我正在运行 Python 3.8.10。 我运行了pip install eel --upgrade
但问题仍然存在。
根据您提供的详细信息,我无法确定确切的问题。 但如果您使用的是 VSC,则可以尝试执行以下这些步骤:
py -m venv.venv
它将创建您的虚拟环境。CTRL
+ SHIFT
+ K
的虚拟环境的 Python 解释器。CTRL
+ J
使用虚拟环境的 Python 解释器启动终端。pip install eel
。hello.py
。web
。web
创建文件hello.html
。 在hello.py
使用此代码:
import eel
eel.init('web')
eel.say_hello_js('Hi from Python')
eel.start('hello.html')
在hello.html
使用此代码:
<!DOCTYPE html>
<html>
<head>
<title>Hello, World!</title>
<!-- Include eel.js - note this file doesn't exist in the 'web' directory -->
<script type="text/javascript" src="/eel.js"></script>
<script type="text/javascript">
eel.expose(say_hello_js); // Expose this function to Python
function say_hello_js(x) {
alert("Hello from " + x);
}
</script>
</head>
<body>
Hello, World!
</body>
</html>
如果您按照这些步骤操作,您应该会看到弹出的警告框。 要从 Python 触发 JS function,您需要在 function 之前使用 eel expose function 像这样eel.expose(your_js_function_name);
. 从 Python 你可以使用 eel 模块调用这个 function 并像这样调用 function 名称eel.your_js_function_name(parameter_if_any)
。 确保在您的 HTML 文件的头部有 eel 脚本元素。 然后是另一个具有所有功能的脚本元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.