其他分享
首页 > 其他分享> > 如何在urwid中创建嵌套的列表框?

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

作者:互联网

是否可以将ListBoxes放在SimpleListWalkers中?我正在尝试制作嵌套的ListBoxes,但是我有这个错误:

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()

解决方法:

根据the manual ListBox是一个包含内部流小部件的框小部件.

小部件类型(框,流和固定)之间的差异在于计算其大小的方法.细节在前面提到的链接中描述.简而言之:ListBox从其容器中获知其大小,但要求其子项自行计算其高度.由于另一个ListBox在里面,它无法提供此值(没有行方法).

解决方案是将内部ListBox包装在BoxAdapter中,使框小部件看起来像行为小部件:

...
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)]))
...

标签:python,listbox,nested,urwid
来源: https://codeday.me/bug/20190517/1121211.html