请用python代码一个轮播图
时间: 2024-06-11 22:04:58 浏览: 73
轮播图代码
这里给出一个基于Python Flask框架和Bootstrap的简单轮播图示例:
HTML模板文件(index.html):
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>轮播图</title>
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css">
<style>
.carousel-item img {
height: 400px;
object-fit: cover;
}
</style>
</head>
<body>
<div class="container">
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
{% for i in range(len(images)) %}
<li data-target="#carouselExampleIndicators" data-slide-to="{{ i }}" {% if i == 0 %}class="active"{% endif %}></li>
{% endfor %}
</ol>
<div class="carousel-inner">
{% for i in range(len(images)) %}
<div class="carousel-item {% if i == 0 %}active{% endif %}">
<img src="{{ images[i] }}" class="d-block w-100" alt="...">
</div>
{% endfor %}
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/popper.js/2.6.0/umd/popper.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.3/js/bootstrap.min.js"></script>
</body>
</html>
```
Python代码:
```python
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
images = [
'https://picsum.photos/800/400?random=1',
'https://picsum.photos/800/400?random=2',
'https://picsum.photos/800/400?random=3',
'https://picsum.photos/800/400?random=4'
]
return render_template('index.html', images=images)
if __name__ == '__main__':
app.run(debug=True)
```
说明:
1. 在HTML模板中,通过Bootstrap的Carousel组件实现轮播图效果;
2. 在Python代码中,通过Flask框架的render_template函数将图片URL列表传递给HTML模板;
3. 运行Python代码后,在浏览器中访问http://localhost:5000,即可看到轮播图效果。
阅读全文