ipywidgets.Textarea 等宽?

Monospace in ipywidgets.Textarea?

如何让我的小部件使用等宽字体?

from ipywidgets import Textarea
Textarea('The world is bigger than you.')

我想显示一些 table 风格的数据。

这可能是一个脆弱的解决方案,但它似乎有效。添加一个 html 魔法部分,给出 css 样式:

%%html
<style>
textarea, input {
    font-family: monospace;
}
</style>

这也有效:

from IPython.display import display
from IPython.core.display import HTML

display(HTML("<style>textarea, input { font-family: monospace; }</style>"))

documentation 讨论了小部件的 style 属性,它使您可以访问 CSS 属性。但是,只有一些属性通过 style.

公开给小部件

解决方法是在 notebook/jupyter/colab 单元格中编辑 CSS 样式,然后显示小部件。

# Adding monospace style
import IPython
IPython.display.HTML('<style> select, textarea, input { font-family: Courier New; } </style>')

# Seems that either the 
# font-family: monospace or font-family: Courier New 
# produce the monospace effect.
# IPython.display.HTML('<style> select, textarea, input { font-family: monospace; } </style>')

# Display your widget
widgets.SelectMultiple(options=sss)
widgets.Textarea(value="Here it is")

它适用于 Textarea、Input、Select、SelectMultiple 和任何其他小部件,因为它们都是 html。


另一种方法是定义 CSS class 的样式,然后将 class 附加到所需的小部件。

IPython.display.HTML('''<style>
.mytext > select,.mytext > textarea   {
    font-style: italic;
    color: blue;
    font-size: 30px;
}
</style>''')

w2=widgets.Textarea(value="Here it is")
w2.add_class("mytext")

w1=widgets.SelectMultiple(options=sss)
w1.add_class('mytext')