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

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

项目: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 = ""
项目:Adwear    作者:Uberi    | 项目源码 | 文件源码
def main():
    palette = [
        ('body','black','dark cyan', 'standout'),
        ('foot','light gray', 'black'),
        ('key','light cyan', 'black', 'underline'),
        ('title', 'white', 'black',),
        ]

    footer_text = [
        ('title', "Fibonacci Set Viewer"), "    ",
        ('key', "UP"), ", ", ('key', "DOWN"), ", ",
        ('key', "PAGE UP"), " and ", ('key', "PAGE DOWN"),
        " move view  ",
        ('key', "Q"), " exits",
        ]

    def exit_on_q(input):
        if input in ('q', 'Q'):
            raise urwid.ExitMainLoop()

    listbox = urwid.ListBox(FibonacciWalker())
    footer = urwid.AttrMap(urwid.Text(footer_text), 'foot')
    view = urwid.Frame(urwid.AttrWrap(listbox, 'body'), footer=footer)
    loop = urwid.MainLoop(view, palette, unhandled_input=exit_on_q)
    loop.run()
项目: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 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)
项目:sshchan    作者:einchan    | 项目源码 | 文件源码
def make_header(self):
        """Populate the row of board buttons on top."""
        # TODO: make it intelligent so it fits in the terminal window
        # and doesn't depend on arbitrary values from config.
        # Keep count of number of printed boards so we won't print too many.
        i = 0
        longest = 0
        btn_list = []

        for board in sorted(self.config.get_boardlist().keys()):
            # This `if` block should be removed when the function learns to
            # calculate horizontal space required.
            if i >= self.config.max_boards:
                break
            if len(board) > longest:
                longest = len(board)
            btn_list.append(CleanButton(
                "/" + board + "/", self.button_press, board))
            i += 1

        # `longest + 2` to account for slashes.
        return ur.AttrMap(ur.GridFlow(btn_list, longest + 2, 1, 0, "center"),
                          "reverse")
项目: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 reply_box(self, button, thr_id):
        subject = ur.Edit(("blue", "Subject: "), wrap="clip")
        name = ur.Edit(("blue", "Name: "), "Anonymous", wrap="clip")
        if thr_id == -1:
            text = ur.Edit(multiline=True)
        else:
            text = ur.Edit(edit_text=">>" + thr_id, multiline=True)
        post_btn = ur.AttrMap(ur.Button(
            "Post", self.add_post, (subject, name, text, thr_id)),
            "green", "b_green")

        box = ur.LineBox(ur.ListBox(ur.SimpleFocusListWalker(
            [name, subject, ur.LineBox(text, "Post text"),
             self.parent.div, post_btn])))

        self.loop.Widget = MyOverlay(
            box, self.loop.baseWidget,
            "center", ("relative", 100), "top", ("relative", 100),
            None, None,
            self.parent.margin, self.parent.margin,
            int(self.loop.dimensions[1] * 0.3),
            int(self.loop.dimensions[1] * 0.3),
            self.parent)
项目: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
        )
项目:scum    作者:CCareaga    | 项目源码 | 文件源码
def delete_tab(self, fname):
        files = self.display.file_names
        # make sure there is more than one file open
        if len(files) > 1:
            index = files.index(fname)
            if index < len(files)-1: # if not last in list
                new_name = files[index+1]
            else: # if last file in list
                new_name = files[index-1]
            # delete file and contents from master lists
            #del self.display.tab_info[fname]
            del files[index]
            del self.display.tabs[index]
            # reset the footer with new tab amount
            foot_col = urwid.Columns(self.display.tabs)
            foot = urwid.AttrMap(foot_col, 'footer')
            if self.display.layout:
                self.display.top.contents['header'] = (foot, None)
            else:
                self.display.top.contents['footer'] = (foot, None)

            self.switch_tabs(new_name)
            del self.display.tab_info[fname]
项目:stellarmagnate    作者:abadger    | 项目源码 | 文件源码
def _sync_widget_lists(self):
        """
        Make sure the widget_list for each column contains the same
        commodities in the same order as the main commodity map
        """
        for column in self.auxiliary_cols:
            column.widget_list.clear()  # pylint: disable=no-member
            for commodity, value in column.data_map.items():
                if isinstance(value, int):
                    formatted_number = format_number(value)
                    if column.money:
                        button = IndexedMenuButton('${}'.format(formatted_number))
                    else:
                        button = IndexedMenuButton('{}'.format(formatted_number))
                else:
                    if value is None:
                        value = " "
                    button = IndexedMenuButton(value)
                urwid.connect_signal(button, 'click', partial(self.handle_commodity_select, commodity))
                column.widget_list.append(urwid.AttrMap(button, None))  # pylint: disable=no-member
项目: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, 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)
项目:boartty    作者:openstack    | 项目源码 | 文件源码
def __init__(self, app, story,
                 enabled_columns, callback=None):
        super(StoryRow, self).__init__('', on_press=callback, user_data=story.key)
        self.app = app
        self.story_key = story.key
        self.enabled_columns = enabled_columns
        self.title = mywid.SearchableText(u'', wrap='clip')
        self.id = mywid.SearchableText(u'')
        self.updated = mywid.SearchableText(u'')
        self.status = mywid.SearchableText(u'')
        self.creator = mywid.SearchableText(u'', wrap='clip')
        self.mark = False
        self.columns = urwid.Columns([], dividechars=1)
        self.row_style = urwid.AttrMap(self.columns, '')
        self._w = urwid.AttrMap(self.row_style, None, focus_map=self.story_focus_map)
        self.update(story)
项目: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
项目: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 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 __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 __init__(self, connection_name):
        try:
            self.connection_name = connection_name
            frame = self.getFrame()
            comp = self.getCommandProcessor()
            self.loop = urwid.MainLoop(urwid.AttrMap(frame, 'bg'),
                                        unhandled_input=comp.onInput,
                                        palette=themes['dark'])

            self.consoleMonitor = ScreepsConsoleMonitor(connection_name,
                                                        self.consoleWidget,
                                                        self.listWalker,
                                                        self.loop)

            comp.setDisplayWidgets(self.loop,
                                   frame,
                                   self.getConsole(),
                                   self.getConsoleListWalker(),
                                   self.getEdit(),
                                   self.consoleMonitor)
            self.loop.run()
        except KeyboardInterrupt:
            exit(0)
项目: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
项目:bbj    作者:desvox    | 项目源码 | 文件源码
def __init__(self):
        self.prefs = bbjrc("load")

        self.mode = None
        self.thread = None
        self.usermap = {}
        self.window_split = False
        self.last_pos = None

        # these can be changed and manipulated by other methods
        self.walker = urwid.SimpleFocusListWalker([])
        self.box = ActionBox(self.walker)
        self.body = urwid.AttrMap(
            urwid.LineBox(
                self.box,
                title=self.prefs["frame_title"],
                **frame_theme()),
            "default"
        )

        self.loop = urwid.MainLoop(
            urwid.Frame(self.body),
            palette=colormap,
            handle_mouse=self.prefs["mouse_integration"])
项目:bbj    作者:desvox    | 项目源码 | 文件源码
def search_prompt(self):
        # XXX: remove if when thread search is supported
        if self.mode != "index":
            return

        popup = OptionsMenu(
            urwid.ListBox(
                urwid.SimpleFocusListWalker([
                    urwid.Text(("button", "Enter a query:")),
                    urwid.AttrMap(StringPrompt(self.search_callback), "opt_prompt"),
                    urwid.Text("Use a blank query to reset the {}.".format(self.mode))
                ])),
            **frame_theme())

        self.loop.widget = urwid.Overlay(
            popup, self.loop.widget,
            align=("relative", 50),
            valign=("relative", 25 if self.window_split else 50),
            width=("relative", 40), height=6)
项目: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')]))
项目: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
                )
            ]
        )
项目: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##################################################
项目:my_ros_tools    作者:groundmelon    | 项目源码 | 文件源码
def __init__(self, prompt_text=u"Input:", default_text=u""):
        close_button = urwid.Button("OK")
        prompt = urwid.Text(prompt_text)
        edit_field = CustomEdit(caption=u'',
                                edit_text=default_text,
                                multiline=False,
                                align='left',
                                wrap='space',
                                allow_tab=False,
                                edit_pos=None,
                                layout=None,
                                mask=None)

        prompt_wrap = urwid.AttrMap(prompt, 'header')
        close_button_wrap = urwid.AttrMap(close_button, 'buttn', 'buttnf')
        edit_field_wrap = urwid.AttrMap(edit_field, 'editcp')

        urwid.connect_signal(close_button, 'click', edit_field.on_finish)
        urwid.connect_signal(edit_field, 'done', self.on_close)

        pile = urwid.Pile([prompt_wrap,
                           edit_field_wrap,
                           urwid.Padding(close_button_wrap, 'center', 6)])
        fill = urwid.Filler(urwid.Padding(pile, 'center', left=1, right=1))
        self.__super.__init__(urwid.AttrWrap(fill, 'popbg'))
项目:selecta    作者:vindolin    | 项目源码 | 文件源码
def __init__(self, list_item, show_hits, match=None):
        self.list_item = list_item

        if match is not None and match is not '' and show_hits is True:
            # highlight the matches
            hits = re.split('({match})'.format(match=re.escape(match)), self.list_item)
            parts = []
            for part in hits:
                if part == match:
                    parts.append(('pattern', part))
                else:
                    parts.append(part)

            text = urwid.AttrMap(
                urwid.Text(parts),
                'line',
                {'pattern': 'pattern_focus', None: 'line_focus'}
            )

        else:
            text = urwid.AttrMap(urwid.Text(self.list_item), 'line', 'line_focus')

        urwid.WidgetWrap.__init__(self, text)
项目:GitChat    作者:shubhodeep9    | 项目源码 | 文件源码
def __init__(
            self, title, login,
            command_caption='Command: (Tab to switch focus to upper '
            'frame, where you can scroll text)\nType exit or quit '
            'to close', 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._output_styles = [s[0] for s in self.PALLETE]
        self.eloop = None
        self.login = login
项目:mongoaudit    作者:Exploit-install    | 项目源码 | 文件源码
def __init__(self, content, header=None, footer=None):
        wlist = []
        if header:
            wlist.append(header)
        wlist.extend([DIV, pad(content)])
        if footer:
            wlist.extend([HR, DIV, pad(footer)])
        wlist.append(DIV)
        card = urwid.AttrMap(urwid.Pile(wlist), 'card')
        urwid.WidgetWrap.__init__(self, card)
项目:mongoaudit    作者:Exploit-install    | 项目源码 | 文件源码
def __init__(self, text, vertical_padding=True):
        content = [urwid.Padding(self.get_content(text), left=3, right=3)]
        if vertical_padding:
            content = [DIV] + content + [DIV]
        lbox = urwid.LineBox(urwid.Pile(content))
        self.__super.__init__(urwid.AttrMap(urwid.Pile(
            [lbox]), 'image button', 'image button focus'))
项目:mongoaudit    作者:Exploit-install    | 项目源码 | 文件源码
def __init__(self, pic, text):
        content = self.get_content(text)
        lbox = urwid.LineBox(urwid.Pile([DIV, urwid.Padding(
            urwid.Columns([(8, pic), content], 4), left=3, right=3), DIV]))
        self.__super.__init__(urwid.AttrMap(urwid.Pile(
            [lbox]), 'image button', 'image button focus'))
项目:mongoaudit    作者:Exploit-install    | 项目源码 | 文件源码
def __init__(self, label="", label_width=15, next_callback=False):
        self.label, self.next_callback = label, next_callback
        self.edit = urwid.Padding(urwid.Edit(), left=1, right=1)
        label = urwid.LineBox(
            urwid.Text(label),
            tlcorner=' ',
            tline=' ',
            lline=' ',
            trcorner=' ',
            blcorner=' ',
            rline=' ',
            brcorner=' ',
            bline=' ')
        lbox = urwid.AttrMap(
            urwid.LineBox(
                self.edit,
                tlcorner=' ',
                tline=' ',
                lline=' ',
                trcorner=' ',
                blcorner=' ',
                rline=' ',
                brcorner=' '),
            'input',
            'input focus')
        cols = urwid.Columns([(label_width, label), lbox])
        urwid.WidgetWrap.__init__(self, cols)
项目:mongoaudit    作者:Exploit-install    | 项目源码 | 文件源码
def get_footer(text, callback):
        return urwid.AttrMap(
            TextButton(
                text,
                align='left',
                on_press=(callback)),
            'button')
项目:mongoaudit    作者:Exploit-install    | 项目源码 | 文件源码
def setup_view(self):
        placeholder = urwid.SolidFill()
        self.loop = urwid.MainLoop(
            placeholder, PALETTE, unhandled_input=self.key_handler)
        self.loop.widget = urwid.AttrMap(placeholder, 'bg')
        #self.loop.widget._command_map['tab'] = 'cursor down'
        #self.loop.widget._command_map['shift tab'] = 'cursor up'
        self.loop.screen.set_terminal_properties(colors=256)
        self.cards.welcome()
项目:mongoaudit    作者:Exploit-install    | 项目源码 | 文件源码
def render(self, card):
        div = urwid.Divider()
        rdiv = urwid.AttrMap(div, 'header')
        header = urwid.Filler(urwid.Pile(
            [rdiv, rdiv, rdiv, rdiv, rdiv]), valign='top')
        h1_text = urwid.Text(('h1', self.name))
        h2_text = urwid.Text(('h2', 'v' + self.version), align='right')
        hg_text = urwid.AttrMap(urwid.Padding(urwid.Columns(
            [h1_text, h2_text]), left=2, right=2, align='center'), 'header')
        body = urwid.Pile([hg_text, rdiv, card, div])
        widget = urwid.Overlay(body, header, 'center', 76, 'top', 'pack', top=1)
        self.loop.widget.original_widget = widget
项目:sshchan    作者:einchan    | 项目源码 | 文件源码
def run(self):
        """This method needs to be called to actually start the display.

        To switch to another view (another Frame widget), use the
        `@widget.setter` property of Loop. To return to earlier view
        (or close a pop-up), use `@widget.deleter`. To interact with the
        body of current Frame, use `@frameBody` property.
        """
        frame = self.MOTD_screen()
        # Top-level widget finished initializing, so let's assign it.
        self.loop.Widget = ur.AttrMap(frame, "bg", None)
        self.loop.run()
项目:sshchan    作者:einchan    | 项目源码 | 文件源码
def MOTD_screen(self):
        """MOTD display method - first screen shown."""
        self.motd_flag = True
        self.header = self.make_header()

        mid = ur.Padding(ur.ListBox(
            ur.SimpleFocusListWalker([
                self.div, ur.Text([("red", "Welcome to "),
                                   ("yellow", "sshchan!\n==========="),
                                   ("red", "========\n"),
                                   ("green", "SERVER: "),
                                   self.config.server_name,
                                   ("green", "\nMOTD:\n")], "center"),
                self.div])), "center", ("relative", 60), self.width,
            self.margin, self.margin)

        # TODO: add currently online users to the footer.
        self.footer = ur.AttrMap(ur.Text(
            " " + self.config.server_name + " " + self.config.version +
            " | Press H for help", align="center"), "reverse", None)

        try:
            with open(self.config.motd, 'r') as m:
                buf = m.read()
        except FileNotFoundError:
            buf = "---sshchan! woo!---"
        motd = ur.Text(buf, "center")
        mid.original_widget.body.append(motd)
        mid.original_widget.body.append(self.div)

        return ur.Frame(mid, self.header, self.footer, focus_part="body")
项目:sshchan    作者:einchan    | 项目源码 | 文件源码
def show_help(self):
        """Create and return Frame object containing help docs."""
        # Flags are gr8 against bugs.
        self.help_flag = True

        help_header = ur.Text(("green", "SSHCHAN HELP"), "center")
        pg1 = ur.Text(
            [("bold", "sshchan "), "is a textboard environment designed \
to run on remote SSH servers with multiple anonymous users simultaneously \
browsing and posting."], "center")
        pg2 = ur.Text(("bold", "Keybindings:"))
        pg3 = ur.Text([("green", "TAB"),
                       (
                           None,
                           " - switch focus between main body and top bar")])
        pg4 = ur.Text(
            [("green", "H h"), (None, " - display this help dialog")])
        pg5 = ur.Text(
            [("green", "B b"), (None, " - view available boards")])
        pg6 = ur.Text(
            [("green", "ESC"),
             (
                 None,
                 " - go back one screen (exits on MOTD screen)")])

        back_btn = ur.AttrMap(
            ur.Button("Back", self.button_press, "back"), "red", "reverse")

        help_body = ur.Padding(ur.ListBox(ur.SimpleListWalker([
            self.div, help_header, self.div, pg1, self.div, pg2,
            pg3, pg4, pg5, pg6, self.div, back_btn])),
            "center", self.width, 0, self.margin, self.margin)

        return ur.AttrMap(ur.Frame(help_body, self.header, self.footer,
                                   "body"), "bg")
项目:sshchan    作者:einchan    | 项目源码 | 文件源码
def print_thread(self, button, thread):
        thr_no = self.board.thread_exists(int(thread))
        thr_body = self.board.get_index()[thr_no]
        replies = ur.SimpleFocusListWalker([])

        subject = ("reverse_red", thr_body[1])
        if subject[1] == "":
            subject = (None, "")

        op = self.parse_post(thr_body[2])
        op_info = ur.Text([("reverse_green", op["name"]),
                           " " + op["stamp"] + " ", subject])
        op_btn = CleanButton(
            "No. " + op["id"], self.reply_box, op["id"])

        op_widget = ur.AttrMap(ur.Columns(
            [("pack", op_info), ("pack", op_btn)], 1), "reverse")

        replies.extend([op_widget, op["text"], self.parent.div])

        if len(thr_body) > 3:
            for postno in range(3, len(thr_body)):
                reply = self.parse_post(thr_body[postno])

                reply_info = ur.Text(
                    [("green", reply["name"]), " " + reply["stamp"]])
                reply_btn = CleanButton(
                    "No. " + reply["id"], self.reply_box, reply["id"])

                reply_widget = ur.Columns(
                    [("pack", reply_info), ("pack", reply_btn)],
                    1)

                replies.extend([reply_widget, reply["text"], self.parent.div])

        contents = ur.ListBox(replies)
        contents.set_focus(0)

        self.loop.Widget = ur.Frame(
            contents, self.parent.header, self.parent.footer, "body")
项目:pytest-ui    作者:martinsmid    | 项目源码 | 文件源码
def __init__(self, test_id, text, escape_method):
        self.escape_method = escape_method

        lines = text.split('\n')
        list_items = [
            urwid.AttrMap(urwid.Text(line), None, focus_map='reversed') for line in lines
        ]

        super(TestResultWindow, self).__init__(
            urwid.ListBox(
                urwid.SimpleFocusListWalker(list_items)
            ),
            title=test_id
        )
项目:pytest-ui    作者:martinsmid    | 项目源码 | 文件源码
def get_list_item(self, test_id, position):
        test_data = self.store.test_data[test_id]
        test_data.update({
            'widget': None,
            'lw_widget': None,
            'position': position,
            'id': test_id,
        })
        test_line = TestLine(test_data)
        test_data['widget'] = test_line
        # logger.debug('widget set for %s: %s', test_id, test_line)
        urwid.connect_signal(test_line, 'click', self.show_test_detail, test_id)
        test_line_attr = urwid.AttrMap(test_line, None, focus_map='reversed')
        test_data['lw_widget'] = test_line_attr
        return test_line_attr
项目:scum    作者:CCareaga    | 项目源码 | 文件源码
def redraw_tabs(self):
         # this is done to ensure that the bottom bar is re-drawn after opening files
        foot_col = urwid.Columns(self.display.tabs)
        foot = urwid.AttrMap(foot_col, 'footer')
        if self.display.layout:
            self.display.top.contents['header'] = (foot, None)
        else:
            self.display.top.contents['footer'] = (foot, None)
项目:scum    作者:CCareaga    | 项目源码 | 文件源码
def update_top_bar(self):
        self.stext = ('header', ['SCUM   ',
                        ('key', 'ESC'), ' Help ',
                        ('key', self.config['save']), ' Save ',
                        ('key', self.config['open']), ' Open ',
                        ('key', self.config['exit']), ' Exit'  ])

        self.tbar = urwid.Text(self.stext)
        self.status = urwid.AttrMap(self.tbar, 'header')

        self.top.contents['header'] = (self.status, None)