[英]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.