建立一个网页Python程序,点击按钮,在文本框中显示"大家好"
时间: 2023-12-27 15:05:21 浏览: 24
好的,以下是一个简单的示例代码,你可以在网页中添加一个按钮,点击后调用该函数并在文本框中显示“大家好”:
```python
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
return render_template('index.html', message='大家好')
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
```
在这个示例中,我们使用了 Flask 框架来搭建网页服务器,当用户请求网址时,会返回一个 HTML 模板文件 `index.html`。在 HTML 文件中,我们添加一个按钮,点击后会向服务器发送 POST 请求,服务器接收到请求后会在文本框中显示“大家好”。
这里是 `index.html` 文件的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>按钮示例</title>
</head>
<body>
<h1>点击按钮</h1>
<form method="post">
<button type="submit">点击</button>
</form>
{% if message %}
<p>{{ message }}</p>
{% endif %}
</body>
</html>
```
注意,在 HTML 文件中我们使用了 Flask 提供的模板引擎,可以在页面中嵌入 Python 变量和表达式。在这个示例中,我们使用了 `{{ message }}` 来显示服务器传递过来的消息。