使用urwid,如何通过按键一次显示一行? [英] Using urwid, how to display one line at a time with keypress?

查看:123
本文介绍了使用urwid,如何通过按键一次显示一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图创建一个简单的功能,该功能在按Enter或向下翻页键时一次显示文本文件中的一行。我希望每次清除这些行。换句话说,我需要暂停程序直到下一次按键。因为它只是显示第一行。我试了一会儿True:无济于事。谢谢您的帮助!

Trying to create a simple function that displays one line from a text file at a time when enter or page down key is pressed. I don't want the lines to clear each time. In other words, I need to pause the program until next key press. As it is it only displays the first line. I tried a while True: to no avail. Thanks for you help!

# Handle key presses
def handle_input(key):
    with open('mobydick_ch1.txt') as f:
        lines = f.readlines()
        line_counter = 0
        if key == 'enter' or key == 'page down':
            text_box.base_widget.set_text(lines[line_counter])
            line_counter += 1
            main_loop.draw_screen()

        elif key == 'Q' or key == 'q':
            raise urwid.ExitMainLoop()


推荐答案

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

That's cool, it looks like you're building a program to read a big text one line at the time? =)

我相信这样做的最好方法是创建一个自定义小部件。

I believe the best way of doing this is to create a custom widget.

也许:

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

然后您可以像使用它一样

And then you can use it like:

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,并且对定制小部件的包装技术也非常感兴趣文字小部件。 =)

I've started using urwid a few months ago and am becoming a bit of a fan of the technique of custom widgets wrapping simple text widgets. =)

这篇关于使用urwid,如何通过按键一次显示一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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