【问题标题】:Adjust the Space Between Two Jupyter Widgets调整两个 Jupyter 小部件之间的间距
【发布时间】:2017-02-07 22:56:45
【问题描述】:

我正在尝试创建一个 Jupyter Notebook 来帮助一些同事以交互方式访问一些数据。我想给他们一堆小部件,允许他们使用不同的标准来过滤数据。

主要是它工作得很好,但我无法调整两个小部件之间的间距,这会让我发疯。

我试过按照here 的说明进行操作,但两个按钮总是紧挨着的。

class Dashboard(object):
    def __init__(self):
        item_layout = Layout(flex='1 1 auto',
                             width='auto')

        toggle = widgets.ToggleButtons(
            options=["Foo", "Bar"],
            value="Foo",
            description="Foobar:",
            disable=False,
            layout=item_layout,
        )

        check = widgets.Checkbox(
            value=True,
            description="Checked",
            disabled=False,
            layout=item_layout,
        )

        box_layout = Layout(display='flex',
                            flex_flow='row',
                            justify_content='space around',
                            width='500px',
                            button_layout='solid',
                            )

        buttons = widgets.Box(children=[
            widgets.interactive(self._set_foobar, foobar=toggle, layout=item_layout),
            widgets.interactive(self._set_checked, checked=check, layout=item_layout),
        ],
            layout=box_layout)

        display(buttons)

    def _set_foobar(self, foobar):
        self._foo = foobar == 'Foo'

    def _set_checked(self, checked):
        self._checked = bool(checked)

如果我随后打开一个 Jupyter 笔记本并执行以下操作:

import dashboard
y = dashboard.Dashboard()

它产生:

如果我不使小部件具有交互性,即children=[toggle, check],它可以完美运行。

有没有办法可以调整交互式小部件之间的间距?

【问题讨论】:

  • 创建一个minimal reproducible example 怎么样?我们需要检查最终结果,以便我们可以看到正在发生的事情并告诉您要更改哪些内容来修复它。你能重现这里的行为吗?
  • 我已经进行了编辑,但这与我所能做的 MCVE 差不多。要查看结果,您需要保存该代码,然后在笔记本中导入和实例化。
  • 好吧,我知道 CSS。我不知道朱皮特。我希望我能帮上忙。祝你好运! :)

标签: python css jupyter-notebook jupyter ipywidgets


【解决方案1】:

在 Jupyter 中,您可以向各种小部件添加类。如果您有一个按钮小部件,请使用add_class() 函数为其添加一个类名。然后,使用display() 函数添加一些CSS。

import ipywidgets as widgets
from IPython.core.display import display, HTML
but_1 = widgets.Button(
     description = 'Button'
)
but_1.add_class("left-spacing-class")
display(HTML(
     "<style>.left-spacing-class {margin-left: 10px;}</style>"
))
display(but_1)

【讨论】: