在 html 代码中运行 python 函数

Running a python function inside html code

提问人:Young Python Programmer 提问时间:10/24/2023 更新时间:10/24/2023 访问量:30

问:

我正在制作一些用于 Web 开发的 python 代码,但我对 html 并不强,所以我正在创建自己的模块来帮助我,到目前为止,我的文件 pyWebDev.py 了这段代码:

def text(content, underlined=False, highlighted=None, bold=False, italic=False, color=None, position=None):
    style = "style='"
    
    if underlined:
        style += "text-decoration: underline; "
    
    if highlighted:
        style += f"background-color: {highlighted}; "
    
    if bold:
        style += "font-weight: bold; "
    
    if italic:
        style += "font-style: italic; "
    
    if color:
        style += f"color: {color}; "

    if position:
        style += f"position: absolute; top: {position[1]}px; left: {position[0]}px; "
    
    style += "'"
    
    return f"<div {style}>{content}</div>"

def entryBox(id, position=None):
    if position:
        style = f"style='position: absolute; top: {position[1]}px; left: {position[0]}px;'"
    else:
        style = ""
    return f"<input type='text' id='{id}' {style}>"

def button(label, onclick=None, position=None):
    if position:
        style = f"style='position: absolute; top: {position[1]}px; left: {position[0]}px;'"
    else:
        style = ""
    
    if onclick:
        return f"<button {style} onclick='{onclick}'>{label}</button>"
    else:
        return f"<button {style}>{label}</button>"

def app():
    "Welcome to Web development module!"


app()

我的 main.py 文件如下所示:

from flask import Flask, render_template_string
import pyWebDev as PWD

app = Flask(__name__)

def clicked():
    print("Hello World")

@app.route('/')
def hello_world():
    html_content = ''
    html_content += PWD.text("Hello World", position=(200, 100))
    html_content += PWD.text("Hello World", position=(200, 200), underlined=True)
    html_content += PWD.button("Hello World", position=(200, 300), onclick="clicked()")
    return render_template_string(html_content)

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=7824)

当我单击该按钮时,它似乎没有调用clicked()函数,我怎样才能使它工作?我想更改模块,以便我可以完全在 main.py 中编码,而无需在那里使用 html。有人可以帮我吗?

python html 函数 烧瓶

评论


答:

1赞 Lenntror 10/24/2023 #1

问题似乎是您在 python 中定义单击的函数,而不是在模块的 javascript 中定义。

因此,任何传递给 HTML-Eventhandler 的函数(例如处理用户单击按钮或那只手的事件)都必须用 Javascript 编写。因此,您可以定义一个插入脚本标签的 python 函数。像这样的东西:onClickonMouseOver

def javascriptOnclick():
    return '<script>function clicked() {console.log("hello world"}</script>'

如果你把它添加到你的变量中,它应该可以工作。因此,您在 html 中运行 python 函数代码的问题的答案是,以您在此处尝试的方式是不可能的。html_code

此外,对于您的问题,我想建议您,您在这里的方法似乎过于复杂且可扩展性不强。因此,我建议您查看 flask 教程。这是一个巨大的教程,可能看起来让人不知所措,但它会在以后为您节省大量时间。