python+eel入门示例

安装eel

pip install eel

py

import eel
import random

# 笑话列表
jokes = [
    "为什么电脑经常生病?因为窗户(Windows)总是开着!",
    "为什么数学书看起来总是很悲伤?因为它里面有太多的问题(problems)",
    "为什么海洋里没有电脑?因为它们总是遇到短路(seals)",
    "为什么冰块感觉很高冷?因为它的幽默感都冻结了。"
]

@eel.expose
def get_joke():
    return random.choice(jokes)

@eel.expose
def say_hello(name):
    return f"Hello, {name}!"

if __name__ == "__main__":
    eel.init(".") #如果是文件夹,就写文件夹名字,我这里html跟python同级
    eel.start("index.html", size=(400, 500))

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Eel应用</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f9;
            color: #333;
            text-align: center;
            padding-top: 50px;
        }

        h1 {
            color: #4a90e2;
        }

        input[type="text"] {
            padding: 10px;
            border-radius: 5px;
            border: 1px solid #ccc;
            width: 200px;
        }

        button {
            background-color: #4a90e2;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        button:hover {
            background-color: #367acb;
        }
    </style>
    <!-- eel.js必须引入,这点其实很像wasm模式 -->
    <script type="text/javascript" src="/eel.js"></script>
</head>
<body>
   <h1>欢迎</h1>
    <input type="text" id="name" placeholder="请输入你的名字"/>
    <button onclick="sayHello()">打招呼</button>
    <div id="greeting"></div>
    <button onclick="getJoke()">讲个笑话</button>
    <div id="joke"></div>

    <script type="text/javascript">
        function sayHello() {
            var name = document.getElementById("name").value;
            eel.say_hello(name)(function(result) {
                document.getElementById("greeting").innerHTML = result;
            });
        }

        function getJoke() {
            eel.get_joke()(function(joke) {
                document.getElementById("joke").innerHTML = joke;
            });
        }
    </script>
</body>
</html>
posted @ 2024-10-16 10:33  朝阳1  阅读(26)  评论(0编辑  收藏  举报