You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为urwid中的ListBox列表项设置自定义样式?

实现带自定义样式的urwid ListBox项

我来帮你搞定这个需求!在urwid中要实现这种多行、多样式的列表项,核心是利用它的文本标记(markup)系统,配合自定义的颜色调色板来完成。下面是完整的解决方案:

完整代码示例

import urwid

class SelectableText(urwid.Text):
    def selectable(self):
        return True
    
    def keypress(self, size, key):
        return key

# 定义所需的颜色样式
palette = [
    ('reveal focus', 'black', 'dark cyan', 'standout'),
    ('title-bold', 'white,bold', ''),
    ('title-green', 'green,bold', ''),
    ('body-text', 'gray', '')
]

# 构建单个列表项的多样式内容
item_markup = [
    # 第一行:绿色加粗开头 + 白色加粗标题
    [('title-green', 'This part should be green'), ('title-bold', ' and is the bold title!')],
    # 第二行灰色正文
    ('body-text', 'These are the first line of grey body text...'),
    # 第三行灰色正文
    ('body-text', 'This is the second line of grey body text...')
]

# 创建可选中的文本项
selectable_item = SelectableText(item_markup)

# 组装ListBox并运行
list_box = urwid.ListBox(urwid.SimpleListWalker([selectable_item]))
urwid.MainLoop(list_box, palette).run()

关键部分解释

  • 调色板(Palette)扩展:
    我们新增了三个样式来匹配你的需求:

    • title-green:用于标题开头的绿色加粗文本
    • title-bold:用于标题剩余部分的白色加粗文本
    • body-text:用于正文两行的灰色文本
  • 多样式文本标记:
    urwid的Text组件支持用列表和元组来定义复杂样式:

    • 第一行用嵌套列表[样式1, 样式2]实现同一行内的多样式拼接
    • 后续两行直接用(样式, 文本)的元组定义灰色正文
  • 可选中项:
    你原来的SelectableText类完全没问题,它让文本项可以被ListBox选中并响应焦点样式(reveal focus)。

扩展:创建多个列表项

如果需要生成多个这样的项,只需要循环创建SelectableText实例即可:

# 批量创建3个列表项
items_list = []
for idx in range(1, 4):
    item_content = [
        [('title-green', f'Item {idx} Green'), ('title-bold', ' Bold Title')],
        ('body-text', f'First body line for item {idx}'),
        ('body-text', f'Second body line for item {idx}')
    ]
    items_list.append(SelectableText(item_content))

list_box = urwid.ListBox(urwid.SimpleListWalker(items_list))
urwid.MainLoop(list_box, palette).run()

内容的提问来源于stack exchange,提问作者Jonathan Shobrook

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:45:47