使用urwid,如何使用按键一次显示一行?

时间:2016-09-06 03:46:33

标签: python-3.x command-line urwid

尝试创建一个简单的函数,在按下输入或向下翻页键时显示文本文件中的一行。我希望每次都清除这些行。换句话说,我需要暂停程序直到下一次按键。因为它只显示第一行。我试了一会儿:没有用。谢谢你的帮助!

{{1}}

1 个答案:

答案 0 :(得分:2)

这很酷,看起来你正在构建一个程序来读取当时的一行大文本? =)

我认为最好的方法是创建一个自定义小部件。

可能是这样的:

class LineReader(urwid.WidgetWrap):
    """Widget wraps a text widget only showing one line at the time"""
    def __init__(self, text_lines, current_line=0):
        self.current_line = current_line
        self.text_lines = text_lines
        self.text = urwid.Text('')
        super(LineReader, self).__init__(self.text)

    def load_line(self):
        """Update content with current line"""
        self.text.set_text(self.text_lines[self.current_line])

    def next_line(self):
        """Show next line"""
        # TODO: handle limits
        self.current_line += 1
        self.load_line()

然后您就可以使用它:

reader = LineReader(list(open('/etc/passwd')))

filler = urwid.Filler(reader)

def handle_input(key):
    if key in ('j', 'enter'):
        reader.next_line()
    if key in ('q', 'Q', 'esc'):
        raise urwid.ExitMainLoop

urwid.MainLoop(filler, unhandled_input=handle_input).run()

我几个月前开始使用urwid,并且正在成为包含简单文本小部件的自定义小部件技术的粉丝。 =)