使用Eel时,如何在JS调用的Python函数中调用JS函数?
问题:Eel框架中Python无法调用JavaScript函数
点击按钮触发JS的testjs函数后,能正常调用Python的testpy函数,但testpy无法调用JS的say_hello_js函数,调整写法、暴露所有函数后仍未解决。
问题根源
你的HTML中脚本加载顺序错误:必须先加载eel.js,再加载自定义的script.js。因为eel.expose()依赖已初始化的eel对象,提前加载自定义脚本会导致eel未定义,say_hello_js函数无法被正确暴露给Python。
修正后的代码
HTML(修正脚本顺序)
<!DOCTYPE html> <html lang="en"> <head> <title>Test</title> <script type="text/javascript" src="../eel.js"></script> <script type="text/javascript" src="./script.js"></script> </head> <body> <button onclick="testjs()">Test</button> </body> </html>
Python代码(无需修改)
import eel import os eel.init(os.path.join(os.path.dirname(__file__),"web")) @eel.expose def testpy(): print("testpy called") eel.say_hello_js("World") eel.start('index.html')
JavaScript代码(无需修改)
function testjs() { console.log("testjs called"); eel.testpy(); } eel.expose(say_hello_js); function say_hello_js(x) { console.log("Hello" + x); }
额外注意事项
- 确保
eel.js的路径正确,相对于HTML文件的位置无误 - 若使用Eel的
--dev模式,可通过浏览器控制台查看是否有eel未定义这类报错,方便快速排查问题
内容的提问来源于stack exchange,提问作者Acrylic
相关产品推荐
相关产品推荐

