2016-09-06 14 views
2

입력 또는 페이지 아래로 키를 누를 때 텍스트 파일의 한 줄을 표시하는 간단한 함수를 만들려고합니다. I 때마다 줄을 지우고 싶지 않습니다. 즉, 다음 키를 누를 때까지 프로그램을 일시 중지해야합니다. 그것은 그대로 첫 번째 줄만 표시합니다. 나는 잠시했지만 사실 : 아무 소용이 없다. 도와 주셔서 감사합니다!urwid를 사용하면 키 누르기로 한 번에 한 줄씩 표시하는 방법은 무엇입니까?

# 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

멋지다. 당시 큰 텍스트 한 줄을 읽는 프로그램을 작성한 것 같습니다. =)

이 작업을 수행하는 가장 좋은 방법은 사용자 정의 위젯을 만드는 것입니다.

아마 같은 것을 :

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 사용하기 시작했습니다과의 팬의 비트가되고 있어요 : 당신이 원하는 사용할 수 있습니다 다음

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

그리고 간단한 텍스트 위젯을 래핑하는 맞춤 위젯 기술. =)