Python urwid 模块,Text() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用urwid.Text()

项目:ecs_explorer    作者:firemanphil    | 项目源码 | 文件源码
def __init__(self, initial_buttons):
        self.list_stack = [initial_buttons]
        self.all_styled_buttons = [urwid.AttrMap(b, None, 'reveal focus')
                                   for b in initial_buttons.items]
        self.list_walker = ChooseFromListWalker(self.all_styled_buttons, self)
        list_box = ChooseFromListBox(self.list_walker)

        column_array = convert_details_to_columns(
            initial_buttons.items[0].retrieve_important_details())

        self.cols = urwid.Columns(
            [('weight', 1, column_array[0]), ('weight', 4, column_array[1])], )
        self.detail_view = False
        self.base_title_text = self.list_stack[-1].items_title
        self.title = urwid.AttrMap(urwid.Text(self.base_title_text + " " + self.EMPTY_FILTER_TEXT), 'title')
        self.cols_title = urwid.AttrMap(urwid.Text(u'Attributes'), 'title')
        self.body = urwid.Pile([(2, urwid.Filler(self.title, valign='top')), list_box, (
            2, urwid.Filler(self.cols_title, valign='top')), self.cols])
        self.before_detail = None
        self.filter_string = ""
项目:mongoaudit    作者:Exploit-install    | 项目源码 | 文件源码
def __init__(self, data, field_labels, btn_label, callbacks):
        self.app = data["app"]
        self.error = False
        self.fields, self.callbacks = [], callbacks
        for label in field_labels:
            self.fields.append(InputField(label, next_callback=self.next))
        input_fields = urwid.Pile(self.fields)
        self.message_field = urwid.Text('')
        error_row = urwid.Columns([(17, urwid.Text('')), self.message_field])
        buttons = [TextButton(btn_label, on_press=self.next)]

        if callbacks['back']:
            buttons.insert(0, TextButton('< Back', align='left', on_press=callbacks['back']))
        footer = urwid.AttrMap(urwid.Columns(buttons), 'button')

        card = Card(urwid.Pile(
            [data["content"], input_fields, error_row]), footer=footer)
        urwid.WidgetWrap.__init__(self, card)
项目:mongoaudit    作者:Exploit-install    | 项目源码 | 文件源码
def __init__(self, title, cred, tests, data):
        self.app = None
        self.tester = data["tester"]
        urn = cred["nodelist"][0][0] + ":" + str(cred["nodelist"][0][1]) + (
            "/" + (cred["database"]) if bool(cred["database"]) else "")

        self.data = {"title": title, "callback": data["callback"],
                     "urn": urn, "num_tests": len(tests)}

        self.progress_text = urwid.Text(
            ('progress', '0/' + str(self.data["num_tests"])))
        running_display = urwid.Columns(
            [(14, urwid.Text(('text', 'Running test'))), self.progress_text])
        self.progress_bar = CustomProgressBar(
            'progress', 'remaining', 0, self.data["num_tests"])
        self.text_running = urwid.Text(('text', ''))
        box = urwid.BoxAdapter(urwid.Filler(
            self.text_running, valign='top'), 2)
        pile = urwid.Pile([running_display, self.progress_bar, DIV, box])
        urwid.WidgetWrap.__init__(self, pile)
项目:mongoaudit    作者:Exploit-install    | 项目源码 | 文件源码
def get_top_row(self, current, options):

        def get_button(sign, text):
            return urwid.AttrMap(TextButton(sign, on_press=(
                lambda _: self.update_view(text))), 'button')

        next_btn = get_button('>', 'next_callback')
        prev_btn = get_button('<', 'prev')
        top_row = []
        if current > 1:
            top_row.append((prev_btn, options('weight', 0)))
        top_row.append((urwid.Padding(urwid.Text(self.get_top_text()),
                                      left=25), options('weight', 1)))
        if current < len(self.result):
            top_row.append((next_btn, options('weight', 0.2)))
        return top_row
项目:mongoaudit    作者:Exploit-install    | 项目源码 | 文件源码
def welcome(self):
        pic = picRead('welcome.bmp', align='right')

        text = urwid.Text([
            ('text bold', self.app.name),
            ('text', ' is a CLI tool for auditing MongoDB servers, detecting poor security '
                     'settings and performing automated penetration testing.\n\n'),
            ('text italic', "\"With great power comes great responsibility\". Unauthorized "
                            "access to strangers' computer systems is a crime "
                            "in many countries. Take care.")
        ])
        button = urwid.AttrMap(
            TextButton(
                "Ok, I'll be careful!", on_press=self.choose_test), 'button')

        card = Card(text, header=pic, footer=button)
        self.app.render(card)
项目:usolitaire    作者:eliasdorneles    | 项目源码 | 文件源码
def __init__(self):
        self.game = Game()
        self._statusbar = urwid.Text(u'Ready')
        self.current_selection = Selection(None, None)
        self._tableau_columns = urwid.Columns([EmptyCardWidget() for _ in range(7)])
        self._top_columns = urwid.Columns([
            EmptyCardWidget(),
            EmptyCardWidget(),
            SpacerWidget(),
            EmptyCardWidget(),
            EmptyCardWidget(),
            EmptyCardWidget(),
            EmptyCardWidget(),
        ])
        self._update_stock_and_waste()
        self._update_foundations()
        self._update_tableaus()

        self.main_layout = urwid.Pile([
            self._top_columns,
            urwid.Divider(),
            self._tableau_columns,
            urwid.Divider(),
            self._statusbar,
        ])
项目:wsstat    作者:Fitblip    | 项目源码 | 文件源码
def __init__(self, client):
        self.client = client

        self.screen = urwid.raw_display.Screen()
        # self.screen = self.DummyScreen()

        self.frame = urwid.Frame(
            client.default_view,
            footer=urwid.Text("", align='center'),
        )

        self.client.frame = self.frame

        self.urwid_loop = urwid.MainLoop(
            self.frame,
            screen=self.screen,
            palette=palette,
            event_loop=self.FixedAsyncLoop(loop=client.loop),
            unhandled_input=client.handle_keypresses,
            pop_ups=True
        )
项目:sshchan    作者:einchan    | 项目源码 | 文件源码
def quit_prompt(self):
        """Pop-up window that appears when you try to quit."""
        # Nothing fancy here.
        question = ur.Text(("bold", "Really quit?"), "center")
        yes_btn = ur.AttrMap(ur.Button(
            "Yes", self.button_press, "quit"), "red", None)
        no_btn = ur.AttrMap(ur.Button(
            "No", self.button_press, "back"), "green", None)

        prompt = ur.LineBox(ur.ListBox(ur.SimpleFocusListWalker(
            [question, self.div, self.div, no_btn, yes_btn])))

        # The only interesting thing in this method is this Overlay widget.
        overlay = MyOverlay(
            prompt, self.loop.baseWidget,
            "center", 20, "middle", 8,
            16, 8,
            parent=self)
        self.loop.Widget = overlay
项目:sshchan    作者:einchan    | 项目源码 | 文件源码
def parse_post(self, post):
        """Read post JSON and return values in easily-readable dictionary."""
        # Old json - without name field
        if len(post) == 3:
            parsed_post = {
                "name": "Anonymous",
                "stamp": self.convert_time(post[0]),
                "id": str(post[1]),
                "text": ur.Text(post[2])
            }
        else:
            parsed_post = {
                "name": post[0],
                "stamp": self.convert_time(post[1]),
                "id": str(post[2]),
                "text": ur.Text(post[3])
            }

        return parsed_post
项目:pytest-ui    作者:martinsmid    | 项目源码 | 文件源码
def init_main_screen(self):
        self.w_filter_edit = urwid.Edit('Filter ')
        aw_filter_edit = urwid.AttrMap(self.w_filter_edit, 'edit', 'edit_focus')
        self.w_status_line = urwid.AttrMap(StatusLine(self.store.get_test_stats), 'statusline', '')
        urwid.connect_signal(self.w_filter_edit, 'change', self.on_filter_change)
        self.init_test_listbox()
        self.w_main = urwid.Padding(
            urwid.Pile([
                ('pack', urwid.Text(u'Python Urwid Test Runner', align='center')),
                ('pack', urwid.Divider()),
                ('pack', aw_filter_edit),
                ('pack', urwid.Divider()),
                self.w_test_listbox,
                ('pack', urwid.Divider()),
                ('pack', self.w_status_line),
            ]),
            left=2, right=2
        )
项目:stellarmagnate    作者:abadger    | 项目源码 | 文件源码
def __init__(self, pubpen):
        self.pubpen = pubpen

        self.exchange_entry = urwid.Text('(C)ommodity Exchange')
        self.port_entry = urwid.Text('(P)ort District')
        self.financial_entry = urwid.Text('(F)inancial')
        self.travel_entry = urwid.Text('(T)ravel')
        self.game_menu_entry = urwid.Text('(M)enu')

        self.menu_entries = urwid.Columns((
            ('weight', 1, urwid.Divider(' ')),
            (len('(C)ommodity Exchange') + 4, self.exchange_entry),
            (len('(P)ort District') + 4, self.port_entry),
            (len('(F)inancial') + 4, self.financial_entry),
            (len('(T)ravel') + 4, self.travel_entry),
            (len('(M)enu') + 4, self.game_menu_entry),
            ('weight', 1, urwid.Divider(' ')),
            ), dividechars=1)

        super().__init__(self.menu_entries)
项目:stellarmagnate    作者:abadger    | 项目源码 | 文件源码
def add_message(self, msg, severity=MsgType.info):
        """
        Add a message to the MessageWindow.

        Reap older messages if there are too many
        """
        if not self._can_print_message:
            self.loop.call_later(self._MIN_TIME_BETWEEN_MESSAGES, self.add_message, msg, severity)
            return

        if severity is MsgType.error:
            msg = urwid.Text(('reversed', msg))
        else:
            msg = urwid.Text(msg)
        self.message_list.append(msg)
        while len(self.message_list) > self._MAX_MESSAGES:
            self.message_list.pop(0)

        self._can_print_message = False
        self.loop.call_later(self._MIN_TIME_BETWEEN_MESSAGES,
                             partial(setattr, self, '_can_print_message', True))
项目:stellarmagnate    作者:abadger    | 项目源码 | 文件源码
def __init__(self, pubpen, spacer=u'u2500'):
        self.pubpen = pubpen

        self.who = urwid.Text(u'\u2524 Name: \u251C')
        self.where = urwid.Text(u'\u2524 Location: \u251C')

        self.left = urwid.Columns([self.who])
        self.right = urwid.Columns([self.where])
        super().__init__((('pack', self.who),
                          ('weight', 1, urwid.Divider(spacer)),
                          ('pack', self.where),
                         ))

        # Connect to backend events
        self.pubpen.subscribe('user.info', self.handle_user_info)
        self.pubpen.subscribe('user.login_success', self.handle_login)
        self.pubpen.subscribe('ship.moved', self.handle_ship_moved)

    #
    # Widget methods
    #
项目:ncTelegram    作者:Nanoseb    | 项目源码 | 文件源码
def __init__(self, Telegram_ui):
        self.Telegram_ui = Telegram_ui
        self.updateLockedauto = False
        self.username_list = []
        self.buffer_writing_text = {}

        # handeling navigation in history
        self.history_own_message = {}
        self.history_pos = 0
        self.cur_text = ""

        self.status_bar = urwid.Text(('status_bar', ' '), align='left')
        self.attr = urwid.AttrMap(self.status_bar, 'status_bar')

        self.widgetEdit = urwid.Edit(TEXT_CAPTION, "", multiline=False)

        self.pile = urwid.Pile([self.attr, self.widgetEdit])
        super().__init__(self.pile)

        self.update_send_widget()
项目:boartty    作者:openstack    | 项目源码 | 文件源码
def __init__(self, title, message, entry_prompt=None,
                 entry_text='', buttons=[], ring=None):
        button_widgets = []
        for button in buttons:
            button_widgets.append(('pack', button))
        button_columns = urwid.Columns(button_widgets, dividechars=2)
        rows = []
        rows.append(urwid.Text(message))
        if entry_prompt:
            self.entry = MyEdit(entry_prompt, edit_text=entry_text, ring=ring)
            rows.append(self.entry)
        else:
            self.entry = None
        rows.append(urwid.Divider())
        rows.append(button_columns)
        listbox = urwid.ListBox(rows)
        super(ButtonDialog, self).__init__(urwid.LineBox(listbox, title))
项目:boartty    作者:openstack    | 项目源码 | 文件源码
def __init__(self, app, board, topic, callback=None):
        super(BoardRow, self).__init__('', on_press=callback,
                                         user_data=(board.key, board.title))
        self.app = app
        self.mark = False
        self._style = None
        self.board_key = board.key
        if topic:
            self.topic_key = topic.key
            self.indent = '  '
        else:
            self.topic_key = None
            self.indent = ''
        self.board_title = board.title
        self.title = mywid.SearchableText('')
        self._setTitle(board.title, self.indent)
        self.title.set_wrap_mode('clip')
        self.active_stories = urwid.Text(u'', align=urwid.RIGHT)
        col = urwid.Columns([
                self.title,
                ('fixed', ACTIVE_COL_WIDTH, self.active_stories),
                ])
        self.row_style = urwid.AttrMap(col, '')
        self._w = urwid.AttrMap(self.row_style, None, focus_map=self.board_focus_map)
        self.update(board)
项目:boartty    作者:openstack    | 项目源码 | 文件源码
def __init__(self, app, project, topic, callback=None):
        super(ProjectRow, self).__init__('', on_press=callback,
                                         user_data=(project.key, project.name))
        self.app = app
        self.mark = False
        self._style = None
        self.project_key = project.key
        if topic:
            self.topic_key = topic.key
            self.indent = '  '
        else:
            self.topic_key = None
            self.indent = ''
        self.project_name = project.name
        self.name = mywid.SearchableText('')
        self._setName(project.name, self.indent)
        self.name.set_wrap_mode('clip')
        self.active_stories = urwid.Text(u'', align=urwid.RIGHT)
        col = urwid.Columns([
                self.name,
                ('fixed', ACTIVE_COL_WIDTH, self.active_stories),
                ])
        self.row_style = urwid.AttrMap(col, '')
        self._w = urwid.AttrMap(self.row_style, None, focus_map=self.project_focus_map)
        self.update(project)
项目:boartty    作者:openstack    | 项目源码 | 文件源码
def __init__(self, topic, callback=None):
        super(TopicRow, self).__init__('', on_press=callback,
                                       user_data=(topic.key, topic.name))
        self.mark = False
        self._style = None
        self.topic_key = topic.key
        self.name = urwid.Text('')
        self._setName(topic.name)
        self.name.set_wrap_mode('clip')
        self.active_stories = urwid.Text(u'', align=urwid.RIGHT)
        col = urwid.Columns([
                self.name,
                ('fixed', ACTIVE_COL_WIDTH, self.active_stories),
                ])
        self.row_style = urwid.AttrMap(col, '')
        self._w = urwid.AttrMap(self.row_style, None, focus_map=self.project_focus_map)
        self._style = 'subscribed-project'
        self.row_style.set_attr_map({None: self._style})
        self.update(topic)
项目:Discurses    作者:topisani    | 项目源码 | 文件源码
def open_confirm_prompt(self, callback, title="", content="",
                            yestxt="Yes", notxt="No", align="center"):
        def create_cb(bool):
            def res(*k, **a):
                callback(bool)
                self.close_pop_up()
            return res
        self.open_pop_up(
            urwid.Filler(urwid.Text(content, align=align)),
            header=urwid.Text(
                title, align='center'),
            footer=urwid.Columns([
                (urwid.Button(yestxt, create_cb(True))),
                (urwid.Button(notxt, create_cb(False))),
            ]),
            height=6,
            width=50)
        self.pop_up.set_focus("footer")
        logger.debug("Confirm prompt text: " + str(content))
项目:Discurses    作者:topisani    | 项目源码 | 文件源码
def update_columns(self):
        cols = []
        names = discurses.processing.shorten_channel_names(
            self.chat_widget.channels, 100)
        for ch in self.chat_widget.channels:
            if ch == self.chat_widget.send_channel:
                cols.append((urwid.AttrMap(
                    urwid.Text(
                        names[ch], align="center"),
                    "send_channel_selector_sel",
                    "send_channel_selector_sel_f"),
                             self.w_cols.options('weight', 1)))
            else:
                cols.append((urwid.AttrMap(
                    urwid.Text(
                        names[ch], align="center"),
                    "send_channel_selector",
                    "send_channel_selector_f"),
                             self.w_cols.options('weight', 1)))
        self.w_cols.contents = cols
项目:Discurses    作者:topisani    | 项目源码 | 文件源码
def __init__(self, chat_widget):
        self.chat_widget = chat_widget
        self.message = FakeMessage(datetime.datetime.min)
        self._selectable = False
        txt = urwid.Text(
            "                                                               \n"
            "                                                               \n"
            "                                                               \n"
            "                                                               \n"
            "< moo >                                                        \n"
            " -----                                                         \n"
            "        \   ^__^                                               \n"
            "         \  (oo)\_______                                       \n"
            "            (__)\       )\/\                                   \n"
            "                ||----w |                                      \n"
            "                ||     ||                                      \n"
            "                                                               \n"
            "                                                               \n"
            "Congratulations! You have reached the top, Thats awesome! Unless "
            "the channel is empty, in which case, meh... big deal.\n\n",
            align=urwid.CENTER)
        w = urwid.Padding(txt, left=5, right=5)
        self.__super.__init__(w)
项目:mongoaudit    作者:stampery    | 项目源码 | 文件源码
def __init__(self, data, field_labels, btn_label, callbacks):
        self.app = data["app"]
        self.error = False
        self.fields, self.callbacks = [], callbacks
        for label in field_labels:
            self.fields.append(InputField(label, next_callback=self.next))
        input_fields = urwid.Pile(self.fields)
        self.message_field = urwid.Text('')
        error_row = urwid.Columns([(17, urwid.Text('')), self.message_field])
        buttons = [TextButton(btn_label, on_press=self.next)]

        if callbacks['back']:
            buttons.insert(0, TextButton('< Back', align='left', on_press=callbacks['back']))
        footer = urwid.AttrMap(urwid.Columns(buttons), 'button')

        card = Card(urwid.Pile(
            [data["content"], input_fields, error_row]), footer=footer)
        urwid.WidgetWrap.__init__(self, card)
项目:mongoaudit    作者:stampery    | 项目源码 | 文件源码
def __init__(self, title, cred, tests, data):
        self.app = None
        self.tester = data["tester"]
        urn = cred["nodelist"][0][0] + ":" + str(cred["nodelist"][0][1]) + (
            "/" + (cred["database"]) if bool(cred["database"]) else "")

        self.data = {"title": title, "callback": data["callback"],
                     "urn": urn, "num_tests": len(tests)}

        self.progress_text = urwid.Text(
            ('progress', '0/' + str(self.data["num_tests"])))
        running_display = urwid.Columns(
            [(14, urwid.Text(('text', 'Running test'))), self.progress_text])
        self.progress_bar = CustomProgressBar(
            'progress', 'remaining', 0, self.data["num_tests"])
        self.text_running = urwid.Text(('text', ''))
        box = urwid.BoxAdapter(urwid.Filler(
            self.text_running, valign='top'), 2)
        pile = urwid.Pile([running_display, self.progress_bar, DIV, box])
        urwid.WidgetWrap.__init__(self, pile)
项目:mongoaudit    作者:stampery    | 项目源码 | 文件源码
def get_top_row(self, current, options):

        def get_button(sign, text):
            return urwid.AttrMap(TextButton(sign, on_press=(
                lambda _: self.update_view(text))), 'button')

        next_btn = get_button('>', 'next_callback')
        prev_btn = get_button('<', 'prev')
        top_row = []
        if current > 1:
            top_row.append((prev_btn, options('weight', 0)))
        top_row.append((urwid.Padding(urwid.Text(self.get_top_text()),
                                      left=25), options('weight', 1)))
        if current < len(self.result):
            top_row.append((next_btn, options('weight', 0.2)))
        return top_row
项目:mongoaudit    作者:stampery    | 项目源码 | 文件源码
def welcome(self):
        pic = picRead('welcome.bmp', align='right')

        text = urwid.Text([
            ('text bold', self.app.name),
            ('text', ' is a CLI tool for auditing MongoDB servers, detecting poor security '
                     'settings and performing automated penetration testing.\n\n'),
            ('text italic', "\"With great power comes great responsibility\". Unauthorized "
                            "access to strangers' computer systems is a crime "
                            "in many countries. Take care.")
        ])
        button = urwid.AttrMap(
            TextButton(
                "Ok, I'll be careful!", on_press=self.choose_test), 'button')

        card = Card(text, header=pic, footer=button)
        self.app.render(card)
项目:stig    作者:rndusr    | 项目源码 | 文件源码
def test_remove(self):
        self.tabs.insert(urwid.Text('Tab3'), urwid.Text('Tab three'))
        self.assertEqual(tuple(t.text for t in self.tabs.titles),
                         ('Tab1', 'Tab2', 'Tab3'))
        self.assertEqual(tuple(t.text for t in self.tabs.contents),
                         ('Tab one', 'Tab two', 'Tab three'))

        self.tabs.remove(self.tabs.get_id(2))
        self.assertEqual(tuple(t.text for t in self.tabs.titles),
                         ('Tab1', 'Tab2'))
        self.assertEqual(tuple(t.text for t in self.tabs.contents),
                         ('Tab one', 'Tab two'))

        self.tabs.remove(1)
        self.assertEqual(tuple(t.text for t in self.tabs.titles),
                         ('Tab1',))
        self.assertEqual(tuple(t.text for t in self.tabs.contents),
                         ('Tab one',))

        self.tabs.remove()
        self.assertEqual(tuple(self.tabs.titles), ())
        self.assertEqual(tuple(self.tabs.contents), ())

        with self.assertRaises(IndexError):
            self.tabs.remove(0)
项目:stig    作者:rndusr    | 项目源码 | 文件源码
def setUp(self):
        self.size = (80, 20)
        self.content = [
            urwid.ListBox(urwid.SimpleFocusListWalker([
                urwid.Edit('Field 1'),
                urwid.Edit('Field 2'),
            ])),

            urwid.ListBox(urwid.SimpleFocusListWalker([
                SelectableText('Row 1'),
                urwid.Edit('', 'Edit field 2'),
                SelectableText('Row 3'),
            ]))
        ]
        self.editbox = self.content[1].body[1]
        self.editbox.edit_pos = 0
        self.tabs = Tabs((urwid.Text('Edit fields'), self.content[0]),
                         (urwid.Text('empty'),),
                         (urwid.Text('Text rows'), self.content[1]))
项目:stig    作者:rndusr    | 项目源码 | 文件源码
def test_focusable_widget_gets_keypress_only_if_visible(self):
        w = Scrollable(
            urwid.Pile([urwid.Text('t1'),
                        urwid.Text('t2'),
                        urwid.Edit('', 'e3')])
        )
        size = (5, 2)

        def press_keys():
            for key in ('backspace', 'backspace', 'f', 'o', 'o'):
                w.keypress(size, key)

        self.check(w, size, text=('t1'.ljust(size[0]),
                                  't2'.ljust(size[0])))
        press_keys()
        self.check(w, size, text=('t1'.ljust(size[0]),
                                  't2'.ljust(size[0])))

        w.set_scrollpos(1)
        self.check(w, size, text=('t2'.ljust(size[0]),
                                  'e3'.ljust(size[0])))
        press_keys()
        self.check(w, size, text=('t2'.ljust(size[0]),
                                  'foo'.ljust(size[0])))
项目:stig    作者:rndusr    | 项目源码 | 文件源码
def test_evaluated_key_does_not_replace_original_key(self):
        # Create a list of widgets that translate 'j' to 'down' in their
        # keypress() methods.
        lst_contents = [self.mk_widget(urwid.Text, str(i), context='item')
                        for i in range(1, 10)]
        self.keymap.bind('j', context='item', action=Key('down'))

        # Create ListBox with separate key context.  If the ListBox gets to
        # handle 'j', it just checks a mark we can look for.
        lst_widget = self.mk_widget(urwid.ListBox, urwid.SimpleFocusListWalker(lst_contents), context='list')
        lst_got_j = FakeAction()
        self.keymap.bind('j', context='list', action=lst_got_j)

        # Make sure everything works regularly
        size = (3, 3)
        self.assert_lines(lst_widget, size, exp_lines=('1  ', '2  ', '3  '), exp_focus_pos=0)
        lst_widget.keypress(size, 'down')
        self.assert_lines(lst_widget, size, exp_lines=('1  ', '2  ', '3  '), exp_focus_pos=1)

        # Do the actual test: Pressing 'j' should pass 'j' to the focused item,
        # which evaluates it to 'down'.  But the list widget must get 'j'.
        lst_widget.keypress(size, 'j')
        self.assert_lines(lst_widget, size, exp_lines=('1  ', '2  ', '3  '), exp_focus_pos=1)
        self.assertEqual(lst_got_j.callnum, 1)
项目:stig    作者:rndusr    | 项目源码 | 文件源码
def test_complete_chain(self):
        self.km.bind('alt-1 alt-2 alt-3', 'foo')

        self.widget.keypress((80,), 'alt-1')
        self.assert_status(keys_given=('alt-1',),
                           widget_text='Original Text',
                           active_keychains=((('alt-1', 'alt-2', 'alt-3'), 'foo'),))

        self.widget.keypress((80,), 'alt-2')
        self.assert_status(keys_given=('alt-1', 'alt-2'),
                           widget_text='Original Text',
                           active_keychains=((('alt-1', 'alt-2', 'alt-3'), 'foo'),))

        self.widget.keypress((80,), 'alt-3')
        self.assert_status(keys_given=(),
                           widget_text='foo1',
                           active_keychains=())
项目:stig    作者:rndusr    | 项目源码 | 文件源码
def test_abort_chain_with_mapped_key(self):
        self.km.bind('alt-1 alt-2 alt-3', 'foo')
        self.km.bind('alt-x', 'bar')

        self.widget.keypress((80,), 'alt-1')
        self.assert_status(keys_given=('alt-1',),
                           widget_text='Original Text',
                           active_keychains=((('alt-1', 'alt-2', 'alt-3'), 'foo'),))

        # Abort the started chain
        self.widget.keypress((80,), 'alt-x')
        self.assert_status(keys_given=(),
                           widget_text='Original Text',
                           active_keychains=())

        # Mapped single-key evaluation works again
        self.widget.keypress((80,), 'alt-x')
        self.assert_status(keys_given=(),
                           widget_text='bar1',
                           active_keychains=())
项目:stig    作者:rndusr    | 项目源码 | 文件源码
def test_abort_chain_with_builtin_key(self):
        self.km.bind('alt-1 alt-2 alt-3', 'foo')

        self.widget.keypress((80,), 'alt-1')
        self.assert_status(keys_given=('alt-1',),
                           widget_text='Original Text',
                           active_keychains=((('alt-1', 'alt-2', 'alt-3'), 'foo'),))

        # This would usually append 'x' to the Edit widget text, but we want it
        # to abort the started chain instead.
        self.widget.keypress((80,), 'x')
        self.assert_status(keys_given=(),
                           widget_text='Original Text',
                           active_keychains=())

        # Now we can change the text again
        self.widget.keypress((80,), 'x')
        self.assert_status(keys_given=(),
                           widget_text='Original Textx',
                           active_keychains=())
项目:stig    作者:rndusr    | 项目源码 | 文件源码
def __init__(self):
        self._text_up = urwid.Text('', align='right')
        self._text_up_limit = urwid.Text('')
        self._text_dn = urwid.Text('', align='right')
        self._text_dn_limit = urwid.Text('')

        spacer = urwid.AttrMap(urwid.SolidFill(' '), 'bottombar')
        self._spacer_canvas = spacer.render((self._SPACER_WIDTH, 1))

        def mkattr(text, attrsname):
            return urwid.AttrMap(urwid.Padding(text), attrsname)

        self._attr_up = mkattr(self._text_up, 'bottombar.bandwidth.up')
        self._attr_up_limit = mkattr(self._text_up_limit, 'bottombar.bandwidth.up')
        self._attr_dn = mkattr(self._text_dn, 'bottombar.bandwidth.down')
        self._attr_dn_limit = mkattr(self._text_dn_limit, 'bottombar.bandwidth.down')

        self._up_limit_width = 0
        self._dn_limit_width = 0
        self._connected = False

        srvapi.status.on_update(self._update_current_rates)
        srvapi.settings.on_update(self._update_rate_limits)
项目:stig    作者:rndusr    | 项目源码 | 文件源码
def display_help(self, topics, lines):
        import urwid
        from ...tui.scroll import (Scrollable, ScrollBar)

        if hasattr(self, 'title'):
            titlew = make_tab_title_widget(str(self.title),
                                           attr_unfocused='tabs.help.unfocused',
                                           attr_focused='tabs.help.focused')
        else:
            titlew = make_tab_title_widget(','.join(topics),
                                           attr_unfocused='tabs.help.unfocused',
                                           attr_focused='tabs.help.focused')

        textw = urwid.AttrMap(Scrollable(urwid.Text('\n'.join(lines))), 'helptext')
        contentw = urwid.AttrMap(ScrollBar(textw), 'scrollbar')
        self.tui.tabs.load(titlew, contentw)
项目:screeps_console    作者:screepers    | 项目源码 | 文件源码
def console(self, comp):
        helpmessage = 'Control console output. `console quiet` to suppress console output and `console reset` to turn it back on.'
        userInput = comp.edit
        user_text = userInput.get_edit_text()
        user_command_split = user_text.split(' ')

        if len(user_command_split) < 2:
            comp.listwalker.append(urwid.Text(('logged_response', helpmessage)))
            return False

        command = user_command_split[1]

        if command == 'quiet':
            comp.consolemonitor.quiet = True
            comp.listwalker.append(urwid.Text(('logged_response', 'Limiting display to user interactions only.')))
        elif command == 'reset' or command == 'verbose':
            comp.consolemonitor.quiet = False
            comp.listwalker.append(urwid.Text(('logged_response', 'Displaying all console output.')))
        else:
            comp.listwalker.append(urwid.Text(('logged_response', helpmessage)))
项目:screeps_console    作者:screepers    | 项目源码 | 文件源码
def list(self, comp):
        command_list = ''
        aliases = list(comp.aliases)
        builtin_list = [method for method in dir(self) if callable(getattr(self, method))]
        commands = builtin_list

        for alias in aliases:
            alias_real = comp.aliases[alias]
            if alias_real not in builtin_list:
                commands.append(alias)

        commands.sort()
        commands.reverse()
        for builtin_command in commands:
            if builtin_command != 'turtle' and not builtin_command.startswith('__'):
                command_list = builtin_command + '  ' + command_list

        comp.listwalker.append(urwid.Text(('logged_response', command_list)))
        return
项目:Drogo    作者:csrgxtu    | 项目源码 | 文件源码
def __init__(self, title, command_caption='Command:  (Tab to switch focus to upper frame, where you can scroll text)', cmd_cb=None, max_size=1000):
        self.header=urwid.Text(title)
        self.model=urwid.SimpleListWalker([])
        self.body=ListView(self.model, lambda: self._update_focus(False), max_size=max_size )
        self.input=Input(lambda: self._update_focus(True))
        foot=urwid.Pile([urwid.AttrMap(urwid.Text(command_caption), 'reversed'),
                        urwid.AttrMap(self.input,'normal')])
        urwid.Frame.__init__(self,
                             urwid.AttrWrap(self.body, 'normal'),
                             urwid.AttrWrap(self.header, 'reversed'),
                             foot)
        self.set_focus_path(['footer',1])
        self._focus=True
        urwid.connect_signal(self.input,'line_entered',self.on_line_entered)
        self._cmd=cmd_cb
        self._output_styles=[s[0] for s in self.PALLETE]
        self.eloop=None
项目:Drogo    作者:csrgxtu    | 项目源码 | 文件源码
def __init__(self, title, command_caption='Command:  (Tab to switch focus to upper frame, where you can scroll text)', cmd_cb=None, max_size=1000):
        self.header=urwid.Text(title)
        self.model=urwid.SimpleListWalker([])
        self.body=ListView(self.model, lambda: self._update_focus(False), max_size=max_size )
        self.input=Input(lambda: self._update_focus(True))
        foot=urwid.Pile([urwid.AttrMap(urwid.Text(command_caption), 'reversed'),
                        urwid.AttrMap(self.input,'normal')])
        urwid.Frame.__init__(self,
                             urwid.AttrWrap(self.body, 'normal'),
                             urwid.AttrWrap(self.header, 'reversed'),
                             foot)
        self.set_focus_path(['footer',1])
        self._focus=True
        urwid.connect_signal(self.input,'line_entered',self.on_line_entered)
        self._cmd=cmd_cb
        self._output_styles=[s[0] for s in self.PALLETE]
        self.eloop=None
项目:memsql-top    作者:memsql    | 项目源码 | 文件源码
def __init__(self, column_meta):
        self.column_meta = column_meta
        self.columns = OrderedDict()
        columns = []
        for name, meta in self.column_meta.columns.items():
            contents = name
            if meta.sort_key:
                contents = [name, ' ', ('head_key', "(%s)" % meta.sort_key.upper())]

            contents = urwid.Text(contents, wrap="clip")
            contents = SortableColumn(contents, 'head')
            self.columns[name] = contents
            if meta.fixed_width:
                assert (contents.original_widget.pack()[0] <=
                        meta.display_width())
                columns.append((meta.display_width(), contents))
            else:
                columns.append(("weight", meta.display_weight(), contents))
        self.sort_column = column_meta.default_sort_key
        self.columns[self.sort_column].update_sort_column(True)
        super(ColumnHeadings, self).__init__(columns, dividechars=1)
项目:memsql-top    作者:memsql    | 项目源码 | 文件源码
def __init__(self, num_cores, max_mem):
        self.cpu_utilbar = urwid.ProgressBar('resource_bar_empty',
                                             'resource_bar', done=num_cores)
        self.mem_utilbar = urwid.ProgressBar('resource_bar_empty',
                                             'resource_bar', done=max_mem)

        super(ResourceMonitor, self).__init__(urwid.Pile([
            urwid.Columns([
                urwid.Text("CPU Util", align="right"),
                self.cpu_utilbar,
                urwid.Divider(),
                urwid.Text("Memory Capacity", align="right"),
                self.mem_utilbar
            ]),
#            urwid.Columns([
#                urwid.Text("CPU Sched Latency"),
#                urwid.ProgressBar('resource_bar_empty', 'resource_bar'),
#                urwid.Divider(),
#                urwid.Text("Memory Paging"),
#                urwid.ProgressBar('resource_bar_empty', 'resource_bar'),
#            ])
        ]))
项目:bbj    作者:desvox    | 项目源码 | 文件源码
def set_escape_key(self, button, args):
        mode = args[0]
        widget = OptionsMenu(
            urwid.ListBox(urwid.SimpleFocusListWalker([
                urwid.Text("Press Enter when done"),
                urwid.AttrMap(KeyPrompt(
                    self.prefs["edit_escapes"][mode],
                    self.save_escape_key,
                    [mode]
                ), "opt_prompt")])),
            title="Set key for " + mode,
            **frame_theme()
        )

        app.loop.widget = urwid.Overlay(
            urwid.AttrMap(widget, "30"),
            app.loop.widget,
            align=("relative", 50),
            valign=("relative", 50),
            width=25, height=5
        )
项目:swarm    作者:3drobotics    | 项目源码 | 文件源码
def menu(title, SSID):
    body = [urwid.Text(title), urwid.Divider()]
    options = []
    for c in SSID:
        button = urwid.Button("[ ] " + c)
        options.append(button)
        #if SSID_DICT[c] == True:
        #    button.set_label(u"DH")
        urwid.connect_signal(button, 'click', item_chosen, c)
        body.append(urwid.AttrMap(button, None, focus_map='reversed'))

    swarmify_button = urwid.Button("Swarmify")
    options.append(swarmify_button)
    urwid.connect_signal(swarmify_button, 'click', swarm_chosen, c)
    body.append(urwid.AttrMap(swarmify_button, None, focus_map='reversed'))

    return urwid.ListBox(urwid.SimpleFocusListWalker(body))
项目:swarm    作者:3drobotics    | 项目源码 | 文件源码
def item_chosen(button, choice):
    if SSID_DICT[choice]:
        button.set_label(u"[ ] " + button.get_label()[4:])
        SSID_DICT[choice] = False
    else:
        button.set_label(u"[*] " + button.get_label()[4:])
        SSID_DICT[choice] = True



    ##response = urwid.Text([u'You chose ', str(SSID_DICT[choice]), u'\n'])
    ##done = urwid.Button(u'Ok')


    ##urwid.connect_signal(done, 'click', exit_program)
    ##main.original_widget = urwid.Filler(urwid.Pile([response,
    ##urwid.AttrMap(done, None, focus_map='reversed')]))
项目:ecs_explorer    作者:firemanphil    | 项目源码 | 文件源码
def toggle_detail(self, item):
        if not self.detail_view:
            self.before_detail = self.body
            detail_text = json.dumps(
                item.detail, indent=4, sort_keys=True, cls=DateTimeEncoder)
            lines = detail_text.split('\n')
            text_lines = [urwid.Text(l) for l in lines]
            list_box = DetailListBox(
                urwid.SimpleFocusListWalker(text_lines), self)
            self.body = list_box
            LAYOUT.contents['body'] = (self.body, None)
            self.detail_view = True
        else:
            self.body = self.before_detail
            LAYOUT.contents['body'] = (self.body, None)
            del self.before_detail
            self.detail_view = False
项目:ecs_explorer    作者:firemanphil    | 项目源码 | 文件源码
def convert_details_to_columns(details):
    labels = []
    data = []
    for detail in details:
        if type(detail[0]) is list:
            labels.extend(detail[0])
        else:
            labels.append(detail[0])
        labels.append('\n')
        data.append(str(detail[1]))
    text2 = '\n'.join(data)
    if len(labels) == 0:
        labels = ''
        text2 = ''
    filler1 = urwid.Filler(urwid.Text(labels, 'left'), valign='top')
    filler2 = urwid.Filler(urwid.Text(text2, 'left'), valign='top')
    return [filler1, filler2]
项目:papis    作者:alejandrogallo    | 项目源码 | 文件源码
def docfield(self, field):
        attr_map = field
        return urwid.Columns(
            [
                (
                    'fixed',
                    self.c1width,
                    urwid.AttrMap(
                        urwid.Text(field + ':'),
                        'field',
                        'field_focus'
                    )
                ),
                urwid.AttrMap(
                    self.fields[field],
                    attr_map
                )
            ]
        )
项目:bmii    作者:psurply    | 项目源码 | 文件源码
def display(self, f):
        def handle_input(key):
            if key in ('q', 'Q'):
                raise urwid.ExitMainLoop()
            elif key in ('right', 'j', ' '):
                if self.slide_id < len(self.sd) - 1:
                    self.slide_id += 1
            elif key in ('left', 'k'):
                if self.slide_id > 0:
                    self.slide_id -= 1
            self.update_display()

        self.load_charset()
        self.sd = list(yaml.load_all(f))
        self.slide_id = 0
        self.update_display()

        txt = urwid.Text(u"Presenting...")
        fill = urwid.Filler(txt, 'bottom')
        urwid.MainLoop(fill, unhandled_input=handle_input).run()
项目:PyAlertMe    作者:jamesleesaunders    | 项目源码 | 文件源码
def __init__(self, title,
                 command_caption='Command:  (Tab to switch focus to upper frame, where you can scroll text)',
                 cmd_cb=None, max_size=1000):
        self.header = urwid.Text(title)
        self.model = urwid.SimpleListWalker([])
        self.body = ListView(self.model, lambda: self._update_focus(False), max_size=max_size)
        self.input = Input(lambda: self._update_focus(True))
        foot = urwid.Pile([urwid.AttrMap(urwid.Text(command_caption), 'reversed'),
                           urwid.AttrMap(self.input, 'normal')])
        urwid.Frame.__init__(self,
                             urwid.AttrWrap(self.body, 'normal'),
                             urwid.AttrWrap(self.header, 'reversed'),
                             foot)
        self.set_focus_path(['footer', 1])
        self._focus = True
        urwid.connect_signal(self.input, 'line_entered', self.on_line_entered)
        self._cmd = cmd_cb
        self._output_styles = [s[0] for s in self.PALLETE]
        self.eloop = None
项目:YtbDwn    作者:praneet95    | 项目源码 | 文件源码
def menuAV(title, avail_stream_both):   ###menu displaying formats with both audio and video ######### 2nd loop
        body = [urwid.Text(title), urwid.Divider()]

        for c in avail_stream_both:
            button = urwid.Button(str(c) + " ----->" + str(c.resolution) + "----->" + str((float(c.get_filesize())/1024)/1024))
            urwid.connect_signal(button, 'click', chosen_URL, c)
            body.append(urwid.AttrMap(button, None, focus_map='reversed'))
        button = urwid.Button("Only Video/Audio Formats")
        urwid.connect_signal(button, 'click', menuVAOnly)
        body.append(urwid.AttrMap(button, None, focus_map='reversed'))

        button = urwid.Button("EXIT")
        urwid.connect_signal(button, 'click', exit_program)
        body.append(urwid.AttrMap(button, None, focus_map='reversed'))

        return urwid.ListBox(urwid.SimpleFocusListWalker(body))

    ##########################################################################333
项目:YtbDwn    作者:praneet95    | 项目源码 | 文件源码
def menuVAOnlyMenu(title, avail_stream_VideoO,avail_stream_audioO): ###menu displaying formats with only audio or video ## must handle cases with audio and video alone ## for 3rd loop
        body = [urwid.Text(title), urwid.Divider()]

        for x in avail_stream_VideoO:
            button = urwid.Button(str(x).split('@',1)[0]  + "---->" +x.resolution  + "----->" + str((float(x.get_filesize())/1024)/1024))
            urwid.connect_signal(button, 'click', chosen_URL, x)
            body.append(urwid.AttrMap(button, None, focus_map='reversed'))
        for x1 in avail_stream_audioO:
            button = urwid.Button(str(x1))
            urwid.connect_signal(button, 'click', chosen_URL, x1)
            body.append(urwid.AttrMap(button, None, focus_map='reversed'))

        button = urwid.Button("EXIT")
        urwid.connect_signal(button, 'click', exit_program)
        body.append(urwid.AttrMap(button, None, focus_map='reversed'))

        return urwid.ListBox(urwid.SimpleFocusListWalker(body))

    #################3333##################################################