如何在urwid中创建嵌套列表框? [英] How to create nested listboxes in urwid?

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

问题描述

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

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

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

推荐答案

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

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

小部件类型(框,流和固定)之间的差异在于计算其大小的方法.详细信息在上述链接中进行了描述.简而言之: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中创建嵌套列表框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆