【问题标题】:How to left align widget label in iPython 3?如何在 iPython 3 中左对齐小部件标签?
【发布时间】:2015-08-04 14:31:00
【问题描述】:

如何左对齐而不是右对齐 iPython 3 小部件(例如 IntSlider)中的标签?我的最终目标是左对齐一组带标签的小部件。这需要左对齐它们的标签,因为标签是每个小部件的最左边的元素。

我已经阅读了 Aligning TextBox Widgets in IPython Notebooks,但是 (a) 它专注于为右对齐标签腾出更多空间,并且 (b) 提议的解决方案似乎不会影响标签宽度。 (顺便说一句,我有兴趣找到可以重置最小标签宽度的单元格可执行代码。)

我也阅读了Change the size of the label in an IPython notebook widget 中的讨论,但似乎没有提供简单的解决方案。

感谢您的帮助。

附录(2015-06-02):

看起来 widget.interactive() 不能很好地与 Jakob 建议的解决方案配合使用。示例:

from IPython.html import widgets
from IPython.display import display
def mySlider(text='', twidth=100, min=0, max=10, value=5):
    c1 = widgets.HBox()
    ints = widgets.IntSlider(min=min, max=max, value=value)
    text = widgets.HTML(text, width=twidth)
    c1.children = (text, ints)
    return c1

s1 = mySlider('Test')
s2 = mySlider('TestTest')
s3 = mySlider('TestTestTest')

def process(a, b, c):
    print([a, b, c])

widgets.interactive(
    process,
    a=s1.children[1].value,
    b=s2.children[1].value,
    c=s3.children[1].value
)

以通常的对齐方式生成滑块标签 a、b、c。

【问题讨论】:

    标签: widget alignment label ipython-notebook


    【解决方案1】:

    您可以简单地将 IntSlider 与 Html 小部件组合来创建您的自定义小部件,例如

    from IPython.html import widgets
    from IPython.display import display
    def mySlider(text='', twidth=100):
        c1 = widgets.HBox()
        ints = widgets.IntSlider()
        text = widgets.HTML(text, width=twidth)
        c1.children = (text, ints)
        return c1
    

    使用这种方法,一些小部件可能看起来像

    s1 = mySlider('Test')
    s2 = mySlider('TestTest')
    s3 = mySlider('TestTestTest')
    display(s1,s2,s3)
    

    更新以使用交互

    要将这些自定义小部件与interact 一起使用,需要添加一些属性和回调。 interact 方法需要widget.descriptionwidget.value 参数来设置交互式小部件。由于我们的容器小部件没有这些参数,它们是手动添加的。此外,有必要将container.valueIntSlider.value 链接起来。这曾经通过简单的赋值实现,更重要的是通过on_trait_change 方法。 最后,interact 方法在widget.on_trait_change 回调上调用process 函数,因此container.on_trait_change 方法被IntSlider.on_trait_change 调用所取代。 更新后的代码如下:

    def mySlider2(text='', twidth=100, min=0, max=10, value=5):
        c1 = widgets.HBox()
        ints = widgets.IntSlider(min=min, max=max, value=value)
        text = widgets.HTML(text, width=twidth)
        c1.children = (text, ints)
        c1.description = text
        c1.value = ints.value
        def update(name, value):
            c1.value = value
        ints.on_trait_change(update,'value')
        c1.on_trait_change = ints.on_trait_change
        return c1
    
    s1a = mySlider2('Test')
    s2a = mySlider2('TestTest')
    s3a = mySlider2('TestTestTest')
    
    widgets.interactive(
        process,
        a=s1a,
        b=s2a,
        c=s3a
    )
    

    【讨论】:

    • 谢谢,@Jakob。请参阅上面的附录。
    猜你喜欢
    • 1970-01-01
    • 2014-12-19
    • 2014-04-11
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    相关资源
    最近更新 更多