如何在 urwid 中创建嵌套列表框?

How to create nested listboxes in urwid?(如何在 urwid 中创建嵌套列表框?)

本文介绍了如何在 urwid 中创建嵌套列表框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将 ListBoxes 放在 SimpleListWalkers 中?我正在尝试制作嵌套列表框,但出现此错误:

Is it possible to put ListBoxes inside of SimpleListWalkers ? I'm trying to make nested ListBoxes, but I have this error :

AttributeError: 'MyListBox' 对象没有属性 'rows'

import urwid

class MyListBox(urwid.ListBox):
    def focus_next(self):
        try: 
            self.body.set_focus(self.body.get_next(self.body.get_focus()[1])[1])
        except:
            pass
    def focus_previous(self):
        try: 
            self.body.set_focus(self.body.get_prev(self.body.get_focus()[1])[1])
        except:
            pass            

def handle_input(event):
    frame.header.set_text("key pressed %s" % event)
    if event == "q":
        raise urwid.ExitMainLoop
    elif event == "up":
        lb.focus_previous()
    elif event == "down" :
        lb.focus_next()        

widgets   = [urwid.AttrMap(urwid.Text(str(x)),None,"focus") for x in xrange(3)]
nested    = [urwid.AttrMap(urwid.Text(str(x)+"_sous"),None,"focus") for x in xrange(3)]
nested_lb = MyListBox(urwid.SimpleListWalker(nested))
lb        = MyListBox(urwid.SimpleListWalker(widgets+[nested_lb]))
frame     = urwid.Frame(lb,header=urwid.Text("Header"))
palette   = [("focus","dark cyan","white")]
loop      = urwid.MainLoop(frame,palette,unhandled_input = handle_input)
loop.screen.set_terminal_properties(colors=256)
loop.run()

推荐答案

根据手册ListBox 是一个盒子小部件,里面包含流小部件.

According to the manual ListBox is a box widget that contains flow widgets inside.

widget 的类型(box、flow 和 fixed)之间的区别在于计算它们大小的方法.详细信息在上述链接中进行了描述.简而言之:ListBox 从它的容器中获知它的大小,但要求它的孩子们自己计算他们的高度.由于另一个 ListBox 在里面,它不能提供这个值(没有 rows 方法).

The difference between the types of widgets (box, flow and fixed) lies in the method of calculating their size. The details are described in the aforementioned link. In short: ListBox is informed about its size from its container, but requires its children to calculate their heights on their own. As another ListBox is inside it can't provide this value (has no rows method).

解决方案是将内部 ListBox 包裹在 BoxAdapter 中,使框小部件的外观和行为类似于流小部件:

The solution is to wrap the inner ListBox in BoxAdapter that makes box widget to look and behave like flow widget:

...
widgets   = [urwid.AttrMap(urwid.Text(str(x)),None,"focus") for x in xrange(3)]
nested    = [urwid.AttrMap(urwid.Text(str(x)+"_sous"),None,"focus") for x in xrange(3)]
nested_lb = MyListBox(urwid.SimpleListWalker(nested))
lb        = MyListBox(urwid.SimpleListWalker(widgets+[urwid.BoxAdapter(nested_lb, 10)]))
...

这篇关于如何在 urwid 中创建嵌套列表框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 urwid 中创建嵌套列表框?

基础教程推荐