如何在ipywidgets中实现垂直方向的轮播组件?
解决方案
修改后的代码可实现垂直方向的轮播效果:
from ipywidgets import Layout, Button, VBox, Label, Box # 调整子元素布局,让按钮宽度适配容器 item_layout = Layout(height='100px', width='100%') items = [Button(layout=item_layout, description=str(i), button_style='warning') for i in range(40)] box_layout = Layout( overflow='hidden scroll', # 设置为垂直方向滚动 border='3px solid black', width='500px', height='400px', # 给容器设置固定高度,触发滚动 flex_flow='column', # 子元素垂直排列 display='flex' ) carousel = Box(children=items, layout=box_layout) VBox([Label('Scroll vertically:'), carousel])
关键修改说明:
- 容器高度:必须给轮播容器设置固定高度(如
400px),否则子元素会将容器撑满,无法触发滚动行为。 - 滚动方向:将
overflow从scroll hidden改为hidden scroll,前者控制横向滚动,后者控制纵向滚动,适配垂直轮播需求。 - 子元素宽度:把
item_layout的min_width='40px'替换为width='100%',让按钮自动填满容器宽度,避免横向留白,匹配垂直轮播的视觉效果。
内容的提问来源于stack exchange,提问作者Сергей Иванов
相关产品推荐
相关产品推荐

