6

是否可以将 ListBoxes 放在 SimpleListWalkers 内?我正在尝试制作嵌套的 ListBox,但出现此错误:

AttributeError: 'MyListBox' object has no attribute '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()
4

1 回答 1

7

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

小部件类型(框、流和固定)之间的区别在于计算它们大小的方法。详细信息在上述链接中进行了描述。简而言之:ListBox从其容器中获知其大小,但要求其子级自行计算其高度。由于另一个ListBox在里面,它不能提供这个值(没有rows方法)。

解决方案是将内部包裹起来ListBoxBoxAdapter使盒子小部件看起来和表现得像流小部件:

...
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)]))
...
于 2014-03-19T15:03:51.807 回答