flask html 按钮,使用Flask,Jinja2,HTML来更新按钮页面
时间: 2024-02-28 22:52:48 浏览: 11
好的,您可以按照以下步骤来实现:
1. 在 Flask 应用程序中设置路由,以返回 HTML 页面:
```python
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
```
2. 创建 HTML 页面,使用 Jinja2 模板引擎来渲染动态内容:
```html
<!DOCTYPE html>
<html>
<head>
<title>Flask Button Example</title>
</head>
<body>
<h1>Flask Button Example</h1>
<form action="{{ url_for('button_clicked') }}" method="POST">
<button type="submit" name="button_pressed" value="clicked">Click Me!</button>
</form>
<p>{{ button_status }}</p>
</body>
</html>
```
在这个 HTML 页面中,我们创建了一个表单,其中包含一个提交按钮。当用户单击按钮时,表单将被提交到 `button_clicked` 路由,并且按钮的值将被设置为 "clicked"。我们还使用了 Jinja2 模板引擎来渲染动态内容,包括按钮的状态。
3. 在 Flask 应用程序中设置 `button_clicked` 路由,以处理按钮点击事件:
```python
@app.route('/button_clicked', methods=['POST'])
def button_clicked():
button_status = 'Button not clicked'
if request.form['button_pressed'] == 'clicked':
button_status = 'Button clicked'
return render_template('index.html', button_status=button_status)
```
在这个路由中,我们检查表单中的按钮值是否为 "clicked"。如果是,我们更新按钮状态,并将其传递回 HTML 页面进行渲染。
4. 运行 Flask 应用程序并访问网址:
```python
if __name__ == '__main__':
app.run(debug=True)
```
现在您可以在浏览器中访问应用程序的 URL,并单击按钮来更新页面上的按钮状态。