2016-09-06 3 views
2

入力またはページダウンキーが押されたときにテキストファイルから1行を表示する単純な関数を作成しようとしています。 I は、その都度回線をクリアしないようにしてください。つまり、次のキーを押すまでプログラムを一時停止する必要があります。そのままでは、最初の行だけが表示されます。私はしばらくしてみました:無駄に。ご協力ありがとうございます!urwidを使用すると、キーを押しながら一度に1行表示する方法はありますか?

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

答えて

2

これは素晴らしいことですが、そのときに大きなテキストを1行読み込むプログラムを作成しているようですね。 =)

これを実行する最良の方法は、カスタムウィジェットを作成することです。

たぶん

のようなもの:

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

そしてあなたのようにそれを使用することができます:私は数ヶ月前urwid使用し始めたとのファンのビットになってきています

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

簡単なテキストウィジェットをラップするカスタムウィジェットのテクニック。 =)

関連する問題