urwid中以粗体显示的部分文本

时间:2017-10-22 15:48:52

标签: urwid

我需要在Urwid中以粗体显示文本字符串的某些部分。是否可以为此实现单个Text小部件?示例:

text = u"Employees - %s, Males - %s, Females - %s" %(emp, male, female)

男性和女性的数值必须以粗体显示。

2 个答案:

答案 0 :(得分:1)

要做这种事情,我喜欢构建包装文本小部件using the urwid.WidgetWrap的自定义小部件的方法,创建一个知道数据结构的小部件。

您还需要register a palette for the bold attributes to apply

这是一个完整的示例代码:

import urwid


# create a palette defining bold attribute
PALETTE = [
    ('bold', 'bold', ''),
]


class BoldValuesList(urwid.WidgetWrap):
    """Show a list of key values, with values in bold
    """
    def __init__(self, values):
        self.separator = u', '
        self.values = values
        self.text = urwid.Text(self._build_text())
        super(BoldValuesList, self).__init__(self.text)

    def _build_text(self):
        # build text markup -- see:
        # http://urwid.org/manual/displayattributes.html#text-markup
        texts = []
        for i, (k, v) in enumerate(self.values):
            texts.append(u'%s: ' % k)
            texts.append(('bold', u'%s' % v))
            if i < len(self.values) - 1:
                texts.append(self.separator)
        return texts


def show_or_exit(key):
    "Exit if user press Q or Esc"
    if key in ('q', 'Q', 'esc'):
        raise urwid.ExitMainLoop()


txt = BoldValuesList([
    (u'Employees', 45),
    (u'Males', 20),
    (u'Females', 25),
])
filler = urwid.Filler(txt, 'top')

# create the main loop wiring the widget, the palette and input handler
loop = urwid.MainLoop(filler, PALETTE, unhandled_input=show_or_exit)
loop.run()

答案 1 :(得分:1)

我认为这应该有效:

text_items = [u"Employees - ", ('bold', emp),
              u", Males - ", ('bold', male),
              u", Females - ", ('bold', female)]
text = urwid.Text(text_items)

正如伊莱亚斯建议的那样,你当然需要提供粗体文字的调色板。

相关问题