You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何控制ipywidgets.ToggleButtons组件的单个按钮宽度

ipywidgets自带的layout参数仅控制ToggleButtons组件的外层容器尺寸,内部单个按钮的样式需要通过自定义CSS或者新版的style参数修改,具体方案如下:

方案1:自定义CSS注入(全版本兼容)

该方法适用于所有版本的ipywidgets,可全局修改所有ToggleButtons样式,也可精准控制单个按钮组:

import ipywidgets as widgets
from IPython.display import display, HTML

# 注入自定义样式,可按需调整宽度、内边距数值
display(HTML("""
<style>
/* 如需只控制特定按钮组,可将下面的选择器替换为 .自定义类名 .widget-toggle-button */
.widget-toggle-button {
    min-width: 60px !important;
    max-width: 100px !important;
    padding: 4px 8px !important; /* 缩小内边距可让按钮更紧凑 */
}
</style>
"""))

# 原ToggleButtons代码
toggle_buttons = widgets.ToggleButtons(
    options=['Slow', 'Regular', 'Fast'],
    description='Speed:',
    disabled=False,
    button_style='',
    tooltips=['Description of slow', 'Description of regular', 'Description of fast'],
)

# 如需精准控制单个按钮组,可给组件添加自定义类,再对应修改CSS选择器
# toggle_buttons.add_class("custom-toggle-group")

display(toggle_buttons)
方案2:原生style参数设置(仅ipywidgets 8.0+版本支持)

8.0及以上版本的ipywidgets已经内置了按钮宽度的配置项,无需注入CSS,直接设置style参数即可:

import ipywidgets as widgets
from IPython.display import display

toggle_buttons = widgets.ToggleButtons(
    options=['Slow', 'Regular', 'Fast'],
    description='Speed:',
    disabled=False,
    button_style='',
    tooltips=['Description of slow', 'Description of regular', 'Description of fast'],
    # 直接设置单个按钮宽度
    style={'button_width': '60px'}
)

display(toggle_buttons)

内容的提问来源于stack exchange,提问作者Rub

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 19:45:05