【问题标题】:Jupyter Notebook: How to change spacing between Text objects inside HBox?Jupyter Notebook:如何更改 HBox 内 Text 对象之间的间距?
【发布时间】:2016-08-11 21:20:24
【问题描述】:

假设我在 Jupyter Notebook 的单元格中有以下代码:

from ipywidgets.widgets import HBox, Text
from IPython.display import display

text1 = Text(description = "text1", width = 100)
text2 = Text(description = "text2", width = 100)
text3 = Text(description = "text3", width = 100)
text4 = Text(description = "text4", width = 100)
text5 = Text(description = "text5", width = 100)
display(HBox((text1, text2, text3, text4, text5)))

它产生以下输出:

如您所见,Text 对象之间存在大量不必要的间距。如何更改间距以使它们留在单元格内?

【问题讨论】:

    标签: python jupyter ipywidgets


    【解决方案1】:

    间距似乎是由于 widget-text 类的宽度被指定为 350 像素的宽度。尝试导入HTML 模块(即from IPython.display import display, HTML)并将HTML('<style> .widget-text { width: auto; } </style>') 插入到单元格中。

    你应该得到这样的结果:

    from ipywidgets.widgets import HBox, Text
    from IPython.display import display, HTML
    
    text1 = Text(description = "text1", width = 100)
    text2 = Text(description = "text2", width = 100)
    text3 = Text(description = "text3", width = 100)
    text4 = Text(description = "text4", width = 100)
    text5 = Text(description = "text5", width = 100)
    
    display(HBox((text1, text2, text3, text4, text5)))
    HTML('<style> .widget-text { width: auto; } </style>')
    

    【讨论】:

    • 你确定在display(HBox((text1, text2, text3, text4, text5)))之后插入一行吗?
    • 嘿,对不起,还有一件事。当我在 HTML 对象正下方添加附加行“print("HI")”时,格式再次变得混乱。你知道这是为什么吗?
    • 我认为如果将HTML('&lt;style&gt; .widget-text { width: auto; } &lt;/style&gt;') 行放在单元格的末尾应该没问题。如果您在该行之后放置一些内容,Jupyter 将使用默认值覆盖您的 CSS。
    【解决方案2】:

    基于 Zarak 的回答,你可以做这样的事情

    from ipywidgets.widgets import HBox, Text
    from IPython.display import display, HTML
    
    text1 = Text(description = "text1", width = 100)
    text2 = Text(description = "text2", width = 100)
    text3 = Text(description = "text3", width = 100)
    text4 = Text(description = "text4", width = 100)
    text5 = Text(description = "text5", width = 100)
    
    display(HBox((text1, text2, text3, text4, text5)))
    display(HTML('<style> .widget-text { width: auto; } </style>'))
    print('hi')
    

    这样,您不需要将HTML('&lt;style&gt; .widget-text { width: auto; } &lt;/style&gt;') 语句作为最后一个语句。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-22
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      相关资源
      最近更新 更多