You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python Eel开发桌面程序时无法获取正确返回值问题求助

问题:Python Eel调用暴露函数返回值异常

使用Python Eel开发桌面程序时,点击按钮后页面未显示预期的"I got it",而是出现异常内容。相关代码如下:

main.py

import sqlite3, eel

eel.init('UI')

@eel.expose
def get_data():
    return "I got it"

eel.start('index.html')

index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./vendor/bootstrap.css">
    <title>Müşteri Takip</title>
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-12 text-center">
                <h2 id="hh2">degiscen mi!</h2>
                <input id="buton" type="button" value="Button">
            </div>
        </div>
    </div>
</body>

<script type="text/javascript" src="/eel.js"></script>
<script src="./vendor/jquery.js"></script>
<script src="index.js"></script>

</html>

index.js

async function yo() {
    document.getElementById('hh2').innerHTML = eel.get_data()();
}
$('#buton').click(function() {
    yo();
})

原因与修复

原因

Eel中从JS调用Python暴露的函数是异步操作,eel.get_data()返回的是一个异步函数对象,直接加()调用不会等待结果返回,拿到的是Promise对象而非实际返回值,所以页面显示异常内容。

修复方案

利用async/await语法等待异步操作完成,修改index.js如下:

async function yo() {
    // 使用await等待Python函数返回结果
    const result = await eel.get_data()();
    document.getElementById('hh2').innerHTML = result;
}
$('#buton').click(function() {
    yo();
})

或者也可以使用回调函数的方式(不依赖async/await):

function yo() {
    eel.get_data()(function(result) {
        document.getElementById('hh2').innerHTML = result;
    });
}
$('#buton').click(function() {
    yo();
})

两种方式都能正确获取Python函数返回的"I got it"并更新页面内容。


内容的提问来源于stack exchange,提问作者burak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 15:31:49