如何处理IPyWidget中按钮的可变宽度

2024-04-20 03:04:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要显示一组按钮。 每个按钮的描述对应于文本的每个单词

为了给一个文本外观,我想让按钮的宽度根据单词的长度在里面。 所以我创建了一个变量,它根据字母的数量给出宽度px

我不知道为什么,但效果不好。它对某些词有效,而对另一些词无效

一些想法? (参见屏幕截图中的“the”一词没有足够的空间,只有…是dísplay

最终的目标当然是让文本看起来像一个我可以点击单词的文本

谢谢

mylist=['loren','ipsum','whapmmtever','loren','ipsum','otra','the','palabra','concept']

list_btns=[]
for i,word in enumerate(mylist):
    # here I try to define the width of the button as depending on the length of the word:
    wordwidth= str(len(word)*12) + 'px'
    wd_raw_save_button = widgets.Button(description=word,
                                        disabled=False,
                                        button_style='success',
                                        tooltip='check the word',
                                        icon='',
                                        layout = Layout(width = wordwidth, margin='0px 0px 0px 0px'))

    list_btns.append(wd_raw_save_button)



showcase=HBox(list_btns)
showcase

how it looks like in jupyter

实际上,在运行voila以可视化结果之后,我得到了以下结果:

enter image description here

这不会给人留下真实文本的印象,即单词之间的间距相同,这是最终目标。 我猜,但我不确定,原因可能是字符的宽度不同,我必须逐个字符计算宽度。但这并不能解释“the”一词不适合按钮。 第二种解释是,底层CSS假设一个最小边界,它覆盖了单词本身。无论如何,我不知道如何控制/影响它


Tags: ofthe文本宽度buttonwidth单词按钮
1条回答
网友
1楼 · 发布于 2024-04-20 03:04:07

小部件的CSS控制有限。似乎在40px左右有一个截止点,文本将被截断。我使用了一个简单的max比较,希望能接近您想要的:

from ipywidgets import *
mylist=['loren','ipsum','whapmmtever','loren','ipsum','otra','the','palabra','concept', 'a'] * 2

list_btns=[]
for i,word in enumerate(mylist):
    # here I try to define the width of the button as depending on the length of the word:
    wordwidth= max(len(word) * 12, 40)
    wordwidth = str(wordwidth) + 'px'
    wd_raw_save_button = widgets.Button(description=word,
                                        disabled=False,
                                        button_style='success',
                                        tooltip='check the word',
                                        icon='',
                                        layout = Layout(width = wordwidth, margin='0px 0px 0px 0px')
                                       )

    list_btns.append(wd_raw_save_button)



showcase=HBox(list_btns, layout= Layout(width='100%'))
showcase

enter image description here

相关问题 更多 >