Python ipywidgets 模块,Button() 实例源码

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

项目:pyxem    作者:pyxem    | 项目源码 | 文件源码
def create_navigator_1d(self):
        import ipywidgets as ipyw
        x_min, x_max = 0, self.signal.axes_manager.navigation_size - 1
        x_text = ipyw.BoundedIntText(value=self.indices[0],
                                     description="Coordinate", min=x_min,
                                     max=x_max,
                                     layout=ipyw.Layout(flex='0 1 auto',
                                                        width='auto'))
        randomize = ipyw.Button(description="Randomize",
                                layout=ipyw.Layout(flex='0 1 auto',
                                                   width='auto'))
        container = ipyw.HBox((x_text, randomize))

        def on_index_change(change):
            self.indices = (x_text.value,)
            self.replot_image()

        def on_randomize(change):
            from random import randint
            x = randint(x_min, x_max)
            x_text.value = x

        x_text.observe(on_index_change, names='value')
        randomize.on_click(on_randomize)
        return container
项目:notebook-molecular-visualization    作者:Autodesk    | 项目源码 | 文件源码
def __init__(self, parent, props):
        super().__init__(layout=ipywidgets.Layout(align_items='flex-end'))
        self.parent = parent
        self.props = props
        self.install_button = ipywidgets.Button()
        self.install_button.add_class('nbv-table-row')
        self.remove_button = ipywidgets.Button(description='remove')
        self.remove_button.add_class('nbv-table-row')
        self.html = ipywidgets.HTML()

        if self.props['writable'] == 'INSTALLED':
            self.chidlren = (self.html,)
        else:
            self.children = (self.html, self.install_button, self.remove_button)
        self.install_button.on_click(self.install)
        self.remove_button.on_click(self.uninstall)
        self.rerender()
项目:notebook-molecular-visualization    作者:Autodesk    | 项目源码 | 文件源码
def __init__(self, image, client):
        self._err = False
        self._client = client
        self.image = image
        self.status = ipy.HTML(layout=ipy.Layout(width="20px"))
        self.html = ipy.HTML(value=image, layout=ipy.Layout(width="400px"))
        self.html.add_class('nbv-monospace')
        self.msg = ipy.HTML(layout=ipy.Layout(width='300px'))
        self.button = ipy.Button(layout=ipy.Layout(width='100px'))
        if mdt.compute.config.devmode:
            self.button.on_click(self.rebuild)
        else:
            self.button.on_click(self.pull)
        self._reactivate_button()
        self._set_status_value()
        super().__init__(children=[self.status, self.html, self.button, self.msg])
项目:py-cloud-compute-cannon    作者:Autodesk    | 项目源码 | 文件源码
def update(self, *args):
        jobstat = self._job.status
        status_display = StatusView(self._job)
        if self._job.inputs:
            input_browser = FileBrowser(self._job.inputs, margin=5, font_size=9)
        else:
            input_browser = ipy.HTML('No input files')
        file_browser = ipy.Tab([input_browser])
        file_browser.set_title(0, 'Input files')

        if jobstat == status.FINISHED:
            output_files = self._job.get_output()
            if self._job.stdout:
                output_files['Standard output'] = self._job.stdout
            if self._job.stderr:
                output_files['Standard error'] = self._job.stderr
            output_browser = FileBrowser(output_files, margin=5, font_size=9)
            file_browser.children = [input_browser, output_browser]
            file_browser.set_title(1, 'Output files')
            self.children = [status_display, file_browser]

        else:
            update_button = ipy.Button(description='Update')
            update_button.on_click(self.update)
            self.children = [status_display, update_button, file_browser]
项目:py-cloud-compute-cannon    作者:Autodesk    | 项目源码 | 文件源码
def __init__(self, filename, fileobj, **kwargs):
        super(FileView, self).__init__(disabled=True)
        self.filename = filename
        self._string = None
        self._current_pos = 0
        self.load_more_button = None
        self.textarea = None
        self._fileobj = fileobj
        # For files that need to be fetched, make a download button
        if hasattr(fileobj, '_fetched') and not fileobj._fetched:
            self.download_button = ipy.Button(description='Download')
            self.children = [self.download_button]
            self.download_button.on_click(self.handle_download_click)
        # if it's file-like, get the _contents
        elif hasattr(fileobj, 'read'):
            try:
                self._string = fileobj.read()
            except UnicodeDecodeError:
                self._string = '[NOT SHOWN - UNABLE TO DECODE FILE]'
            self.render_string()
        # Just display a string
        else:
            self._string = fileobj
            self.render_string()
项目:py-cloud-compute-cannon    作者:Autodesk    | 项目源码 | 文件源码
def render_string(self):
        height = '%spx' % min(self._string.count('\n') * 16 + 36, 600)
        try:
            self.textarea = ipy.Textarea(self._string[:self.CHUNK],
                                         layout=Layout(width='100%', height=height))
        except traitlets.TraitError:
            self.textarea = ipy.Textarea('[NOT SHOWN - UNABLE TO DECODE FILE]',
                                         layout=Layout(height='300px',
                                                       **self.TEXTAREA_KWARGS))
            return
        finally:
            self.children = [self.textarea]
            self._current_pos = self.CHUNK

        if len(self._string) > self.CHUNK:
            self.textarea.value += self.TRUNCATE_MESSAGE
            self.load_more_button = ipy.Button(description='See more')
            self.load_more_button.on_click(self.load_more)
            self.children = self.children + (self.load_more_button,)
项目:pyxem    作者:pyxem    | 项目源码 | 文件源码
def create_navigator_2d(self):
        import ipywidgets as ipyw
        x_min, y_min = 0, 0
        x_max, y_max = self.signal.axes_manager.navigation_shape
        x_max -= 1
        y_max -= 1
        x_text = ipyw.BoundedIntText(value=self.indices[0], description="x",
                                     min=x_min, max=x_max,
                                     layout=ipyw.Layout(flex='0 1 auto',
                                                        width='auto'))
        y_text = ipyw.BoundedIntText(value=self.indices[1], description="y",
                                     min=y_min, max=y_max,
                                     layout=ipyw.Layout(flex='0 1 auto',
                                                        width='auto'))
        randomize = ipyw.Button(description="Randomize",
                                layout=ipyw.Layout(flex='0 1 auto',
                                                   width='auto'))
        container = ipyw.HBox((x_text, y_text, randomize))

        def on_index_change(change):
            self.indices = (x_text.value, y_text.value)
            self.replot_image()

        def on_randomize(change):
            from random import randint
            x = randint(x_min, x_max)
            y = randint(y_min, y_max)
            x_text.value = x
            y_text.value = y

        x_text.observe(on_index_change, names='value')
        y_text.observe(on_index_change, names='value')
        randomize.on_click(on_randomize)
        return container
项目:stomatameasurer    作者:TeamMacLean    | 项目源码 | 文件源码
def _update(self, box):

        def on_click(b):
            if b.description == 'up one level':
                self.path = os.path.split(self.path)[0]
            else:
                self.path = self.path + "/" + b.description
            self._update_files()
            self._update(box)

        buttons = []
        # if self.files:
        button = widgets.Button(description='up one level', background_color='#aaaaaa')
        button.on_click(on_click)
        buttons.append(button)
        for f in self.dirs:
            button = widgets.Button(description=f, background_color='#d0d0ff')
            button.on_click(on_click)
            buttons.append(button)
        for f in self.files:
            button = widgets.Button(description=f)
            button.on_click(on_click)
            buttons.append(button)
        box.children = tuple([widgets.HTML("You have selected: <h3>%s</h3>" % (self.path,))] + buttons)
项目:cube_browser    作者:SciTools    | 项目源码 | 文件源码
def __init__(self, initial_value='', default=''):
        if initial_value == '':
            try:
                initial_value = iris.sample_data_path('')
            except ValueError:
                initial_value = ''
        # Define the file system path for input files.
        self._path = ipywidgets.Text(
            description='Path:',
            value=initial_value,
            width="100%")
        # Observe the path.
        self._path.observe(self._handle_path, names='value')
        # Use default path value to initialise file options.
        options = []
        if os.path.exists(self._path.value):
            options = glob.glob('{}/*'.format(self._path.value))
            options.sort()
        default_list = []
        for default_value in default.split(','):
            if default_value in options:
                default_list.append(default_value)
        default_tuple = tuple(default_list)

        # Defines the files selected to be loaded.
        self._files = ipywidgets.SelectMultiple(
            description='Files:',
            options=OrderedDict([(os.path.basename(f), f)
                                 for f in options]),
            value=default_tuple,
            width="100%"
        )
        self.deleter = ipywidgets.Button(description='delete tab',
                                         height='32px', width='75px')
        hbox = ipywidgets.HBox(children=[self._files, self.deleter])
        self._box = ipywidgets.Box(children=[self._path, hbox], width="100%")
项目:scikit-dataaccess    作者:MITHaystack    | 项目源码 | 文件源码
def _update(self, box):

        def on_click(b):
            if b.description == '..':
                self.path = os.path.split(self.path)[0]
            else:
                self.path = os.path.join(self.path, b.description)
            self._update_files()
            self._update(box)

        buttons = []

        for f in self.dirs:
            button = widgets.Button(description=f, background_color='#d0d0ff', layout=widgets.Layout(width='50%'))
            button.on_click(on_click)
            buttons.append(button)
        for f in self.files:
            button = widgets.Button(description=f, layout=widgets.Layout(width='50%'))
            button.style.button_color = 'powderblue'
            button.on_click(on_click)
            buttons.append(button)

        box.children = tuple([widgets.HTML("%s" % (self.path,))] + buttons)


# example usage:
#   f = FileBrowser()
#   f.widget()
#   <interact with widget, select a path>
# in a separate cell:
#   f.path # returns the selected path
项目:altair_widgets    作者:altair-viz    | 项目源码 | 文件源码
def _create_shelf(self, i=0):
        """
        Creates shelf to plot a dimension (includes buttons
        for data column, encoding, data type, aggregate)

        """
        encodings = _get_encodings()

        cols = widgets.Dropdown(options=self.columns, description='encode')
        encoding = widgets.Dropdown(options=encodings, description='as',
                                    value=encodings[i])
        encoding.layout.width = '20%'

        adv = widgets.VBox(children=[], visible=False)

        button = widgets.Button(description='options')
        button.on_click(self._show_advanced)
        button.layout.width = '10%'

        # The callbacks when the button is clicked
        encoding.observe(self._update, names='value')
        cols.observe(self._update, names='value')

        # Making sure we know what row we're in in the callbacks
        encoding.row = cols.row = button.row = adv.row = i

        # Have the titles so we know what button we're editing
        encoding.title = 'encoding'
        cols.title = 'field'
        button.title = 'button'
        adv.title = 'advanced'

        return widgets.HBox([cols, encoding, button, adv])
项目:altair_widgets    作者:altair-viz    | 项目源码 | 文件源码
def _generate_controller(self, ndims):
        marks = _get_marks()
        # mark button
        mark_choose = widgets.Dropdown(options=marks, description='Marks')
        mark_choose.observe(self._update, names='value')
        mark_choose.layout.width = '20%'
        mark_choose.row = -1
        mark_choose.title = 'mark'

        # mark options button
        mark_but = widgets.Button(description='options')
        mark_but.layout.width = '10%'
        mark_but.row = -1
        mark_but.title = 'mark_button'

        # Mark options
        mark_opt = widgets.VBox(children=[], visible=False)
        mark_but.on_click(self._show_advanced)
        mark_opt.title = 'mark_options'
        mark_opt.layout.width = '300px'

        add_dim = widgets.Button(description='add encoding')
        add_dim.on_click(self._add_dim)

        to_altair = widgets.Button(description='chart.to_altair()')
        to_altair.on_click(self._to_altair)

        dims = [self._create_shelf(i=i) for i in range(ndims)]

        choices = dims + [widgets.HBox([add_dim, to_altair, mark_choose,
                                        mark_but, mark_opt])]
        return widgets.VBox(choices)
项目:notebook-molecular-visualization    作者:Autodesk    | 项目源码 | 文件源码
def __init__(self):
        self.client = None
        self.warning = ipy.HTML(description='<b>Engine status:</b>', value=SPINNER)
        self.devmode_label = ipy.Label('Use local docker images (developer mode)',
                                       layout=ipy.Layout(width='100%'))
        self.devmode_button = ipy.Checkbox(value=mdt.compute.config.devmode,
                                           layout=ipy.Layout(width='15px'))
        self.devmode_button.observe(self.set_devmode, 'value')

        self.engine_config_description = ipy.HTML('Docker host with protocol and port'
                                                  ' (e.g., <code>http://localhost:2375</code>).'
                                                  ' If blank, this'
                                                  ' defaults to the docker engine configured at '
                                                  'your command line.',
                                                  layout=ipy.Layout(width='100%'))
        self.engine_config_value = ipy.Text('blank', layout=ipy.Layout(width='100%'))
        self.engine_config_value.add_class('nbv-monospace')

        self.image_box = ipy.Box()

        self._reset_config_button = ipy.Button(description='Reset',
                                               tooltip='Reset to applied value')
        self._apply_changes_button = ipy.Button(description='Apply',
                                                tooltip='Apply for this session')
        self._save_changes_button = ipy.Button(description='Make default',
                                               tooltip='Make this the default for new sessions')
        self._reset_config_button.on_click(self.reset_config)
        self._apply_changes_button.on_click(self.apply_config)
        self._save_changes_button.on_click(self.save_config)

        self.children = [self.warning,
                         VBox([self.engine_config_description,
                               self.engine_config_value]),
                         HBox([self._reset_config_button,
                               self._apply_changes_button,
                               self._save_changes_button]),
                         HBox([self.devmode_button, self.devmode_label]),
                         self.image_box]
        self.reset_config()
        super().__init__(children=self.children)
        self.connect_to_engine()
项目:notebook-molecular-visualization    作者:Autodesk    | 项目源码 | 文件源码
def __init__(self):
        super().__init__(
                **process_widget_kwargs(dict(flex_flow='column')))
        self.repo_field = ipy.Text(description='Image repository')
        self.version_field = ipy.Text(description='Image version')

        self._reset_config_button = ipy.Button(description='Reset',
                                               tooltip='Reset to current configuration')

        self._apply_changes_button = ipy.Button(description='Apply',
                                                tooltip='Apply for this session')
        self._save_changes_button = ipy.Button(description='Make default',
                                               tooltip='Make this the default for new sessions')
        self._pull_button = ipy.Button(description='Pull images',
                                       tooltip=
                                       'Download all moldesign images to the compute engine')

        self.children = (HBox([self.repo_field, self.version_field]),
                         HBox([self._reset_config_button,
                                                self._apply_changes_button,
                                                self._pull_button]))

        self._reset_config_button.on_click(self.reset_config)
        self._apply_changes_button.on_click(self.apply_config)
        self._save_changes_button.on_click(self.save_config)
        self._test_button.on_click(self.test_connection)
项目:notebook-molecular-visualization    作者:Autodesk    | 项目源码 | 文件源码
def __init__(self, paramlist, paramdefs, title=None):
        super(Configurator, self).__init__(layout=ipy.Layout(display='flex',
                                                             flex_flow='column',
                                                             align_self='flex-start',
                                                             align_items='stretch',
                                                             max_width='100%'))
        self.paramlist = paramlist
        self.paramdefs = paramdefs

        self.apply_button = ipy.Button(description='Apply')
        self.apply_button.on_click(self.apply_values)

        self.reset_button = ipy.Button(description='Reset')
        self.reset_button.on_click(self.reset_values)
        self.buttons = ipy.Box([self.reset_button, self.apply_button],
                               layout=ipy.Layout(align_self='center'))

        self.selectors = collections.OrderedDict([(p.name, ParamSelector(p)) for p in paramdefs])
        self.reset_values()

        title = utils.if_not_none(title, 'Configuration')
        self.title = ipy.HTML('<center><h4>%s</h4></center><hr>' % title,
                              align_self='center')

        self.currentconfig = ipy.Textarea(description='<i>Current params</i>',
                                          disabled=True,
                                          value=self._pretty_print_config(),
                                          layout=ipy.Layout(width='350px', min_height='300px',
                                                            max_height='500px',
                                                            display='flex', flex_flow='column'))
        self.middle = HBox([VBox(list(self.selectors.values())), self.currentconfig])
        self.children = [self.title, self.middle, self.buttons]
项目:notebook-molecular-visualization    作者:Autodesk    | 项目源码 | 文件源码
def __init__(self, mol):
        super().__init__(mol)

        self._atomset = collections.OrderedDict()

        self.atom_listname = ipy.Label('Selected atoms:', layout=ipy.Layout(width='100%'))
        self.atom_list = ipy.SelectMultiple(options=list(self.viewer.selected_atom_indices),
                                            layout=ipy.Layout(height='150px'))
        traitlets.directional_link(
            (self.viewer, 'selected_atom_indices'),
            (self.atom_list, 'options'),
            self._atom_indices_to_atoms
        )

        self.select_all_atoms_button = ipy.Button(description='Select all atoms')
        self.select_all_atoms_button.on_click(self.select_all_atoms)

        self.select_none = ipy.Button(description='Clear all selections')
        self.select_none.on_click(self.clear_selections)

        self.representation_buttons = ipy.ToggleButtons(options=['stick','ribbon', 'auto', 'vdw'],
                                                        value='auto')
        self.representation_buttons.observe(self._change_representation, 'value')
项目:ipython-IDV    作者:Unidata    | 项目源码 | 文件源码
def make_button(label, callback, extra=None):
        """Utility to make a button widget"""
        b = widgets.Button(
            description=label,
            disabled=False,
            button_style='',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip=label,
            )
        b.extra = extra
        b.on_click(callback)
        return b
项目:paramnb    作者:ioam    | 项目源码 | 文件源码
def ActionButton(*args, **kw):
    """Returns a ipywidgets.Button executing a paramnb.Action."""
    kw['description'] = str(kw['name'])
    value = kw["value"]
    w = ipywidgets.Button(*args,**kw)
    if value: w.on_click(value)
    return w
项目:paramnb    作者:ioam    | 项目源码 | 文件源码
def get_state(self, key=None, drop_defaults=False):
        # HACK: Lets this composite widget pretend to be a regular widget
        # when included into a layout.
        if key in ['value', '_options_labels']:
            return super(CrossSelect, self).get_state(key)
        return self._composite.get_state(key)


# Composite widget containing a Dropdown and a Button in an HBox.
# Some things are routed to/from the Dropdown, others to/from the
# composite HBox.
项目:paramnb    作者:ioam    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        self._select = Dropdown(*args,**kwargs)
        self._edit = Button(description='...',
                            layout=Layout(width='15px'))
        self._composite = HBox([self._select,self._edit])
        super(DropdownWithEdit, self).__init__()
        self.layout = self._composite.layout
        # so that others looking at this widget's value get the
        # dropdown's value
        traitlets.link((self._select,'value'),(self,'value'))
        self._edit.on_click(lambda _: editor(self._select.value))
        self._select.observe(lambda e: self._set_editable(e['new']),'value')
        self._set_editable(self._select.value)
项目:snowballing    作者:JoaoFelipe    | 项目源码 | 文件源码
def __init__(self, mode="text"):
        self.mode_widget = Dropdown(
            options={
                'BibTeX': 'bibtex',
                'Text': 'text',
                '[N] author name place other year': 'citation',
                'Quoted': 'quoted',
            },
            value=mode
        )
        self.button_widget = Button(
            description="Set article_list variable",
            disabled=mode not in ("citation", "bibtex")
        )
        self.frompdf_widget = Textarea()
        self.output_widget = Textarea()
        self.label_widget = Label()
        self.frompdf_widget.observe(self.write)
        self.mode_widget.observe(self.select)
        self.button_widget.on_click(self.set_variable)
        self.view = VBox([
            HBox([self.mode_widget, self.button_widget, self.label_widget]),
            HBox([self.frompdf_widget, self.output_widget])
        ])

        self.frompdf_widget.layout.height = "500px"
        self.output_widget.layout.height = "500px"
        self.frompdf_widget.layout.width = "50%"
        self.output_widget.layout.width = "50%"
        self.backup = ""
        self.ipython = get_ipython()
项目:snowballing    作者:JoaoFelipe    | 项目源码 | 文件源码
def create_custom_button(self, tup):
        """Create custom button based on config.FORM_BUTTONS tuple"""
        button = Button(description=tup[0])
        def function(b):
            for key, value in tup[1].items():
                getattr(self, key).value = value
            self.show(clear=True)
        button.on_click(function)
        return button
项目:snowballing    作者:JoaoFelipe    | 项目源码 | 文件源码
def __init__(self, querier, citation_var, citation_file=None, debug=False, start=None, load=True):
        from .selenium_scholar import URLQuery
        reload()
        self.querier = querier
        work = work_by_varname(citation_var)
        citation_file = citation_file or getattr(work, "citation_file", citation_var)
        self.navigator = ArticleNavigator(citation_var, citation_file, backward=False, force_citation_file=False)
        self.query = URLQuery(self.navigator.work.scholar, start)
        self.next_page_widget = Button(description='Next Page', icon='fa-arrow-right')
        self.reload_widget = Button(description='Reload', icon='fa-refresh')
        self.previous_page_widget = Button(description='Previous Page', icon='fa-arrow-left')
        self.debug_widget = ToggleButton(value=debug, description="Debug")
        self.page_number_widget = Label(value="")
        self.next_page_widget.on_click(self.next_page)
        self.reload_widget.on_click(self.reload)
        self.previous_page_widget.on_click(self.previous_page)

        self.view = Tab([
            VBox([
                HBox([
                    self.previous_page_widget,
                    self.reload_widget,
                    self.next_page_widget,
                    self.debug_widget,
                    self.page_number_widget
                ]),
                self.navigator.output_widget,
            ]),
            self.navigator.view
        ])
        self.view.set_title(0, "Page")
        self.view.set_title(1, "Article")
        if load:
            self.reload(None)
项目:snowballing    作者:JoaoFelipe    | 项目源码 | 文件源码
def __init__(self, querier, worklist, force=False, debug=False, index=0):
        reload()
        self.worklist = worklist
        self.force = force
        self.querier = querier
        self.next_page_widget = Button(description='Next Work', icon='fa-arrow-right')
        self.reload_widget = Button(description='Reload', icon='fa-refresh')
        self.previous_page_widget = Button(description='Previous Work', icon='fa-arrow-left')
        self.debug_widget = ToggleButton(value=debug, description="Debug")
        self.textarea_widget = ToggleButton(value=False, description="TextArea")
        self.page_number_widget = Label(value="")
        self.output_widget = Output()
        self.next_page_widget.on_click(self.next_page)
        self.reload_widget.on_click(self.reload)
        self.previous_page_widget.on_click(self.previous_page)
        self.textarea_widget.observe(self.show)
        self.view = VBox([
            HBox([
                self.previous_page_widget,
                self.reload_widget,
                self.next_page_widget,
                self.debug_widget,
                self.textarea_widget,
                self.page_number_widget
            ]),
            self.output_widget
        ])
        self.index = index
        self.varname = ""
        self.work = None
        self.articles = []
        self.reload(show=False)
项目:snowballing    作者:JoaoFelipe    | 项目源码 | 文件源码
def new_button(description, function):
    """Create a new Button widget and set its on_click callback"""
    button = Button(description=description)
    button.on_click(function)
    return button
项目:yuuno    作者:Irrational-Encoding-Wizardry    | 项目源码 | 文件源码
def __init__(self, clip=None, *args, **kwargs):
        super(Preview, self).__init__(*args, **kwargs, clip=clip)
        self.links = [directional_link((self._ui_intslider, 'value'), (self, 'frame'))]

        prev = Button(icon="fa-step-backward", layout=Layout(width="50px"))
        prev.on_click(lambda s: self.step(-1))
        next = Button(icon="fa-step-forward", layout=Layout(width="50px"))
        next.on_click(lambda s: self.step(1))

        self.children = [
            HBox([prev, next, self._ui_intslider]),
            self._current
        ]
项目:cube_browser    作者:SciTools    | 项目源码 | 文件源码
def __init__(self, url=''):
        self.file_pickers = []
        if url:
            o = urlparse(url)
            query = parse_qs(o.query)
            pwd, = query.get('pwd', [''])
            for fname in query.get('files', []):
                self.file_pickers.append(FilePicker(pwd, os.path.join(pwd, fname)))
            for fpath in query.get('folders', []):
                self.file_pickers.append(FilePicker(fpath))
        if not self.file_pickers:
            self.file_pickers.append(FilePicker())

        # Define load action.
        self._load_button = ipywidgets.Button(description="load these files")
        self._load_button.on_click(self._handle_load)
        self._file_tab_button = ipywidgets.Button(description="add tab")
        self._file_tab_button.on_click(self._handle_new_tab)

        self._subplots = ipywidgets.RadioButtons(description='subplots',
                                                 options=[1, 2])
        self._subplots.observe(self._handle_nplots, names='value')

        # Plot action button.
        self._plot_button = ipywidgets.Button(description="Plot my cube")
        self._plot_button.on_click(self._goplot)

        # Configure layout of the Explorer.
        self._plot_container = ipywidgets.Box()
        # Define a Tab container for the main controls in the browse interface.
        children = [fp.box for fp in self.file_pickers]
        self.ftabs = ipywidgets.Tab(children=children)
        children = [self._load_button, self._file_tab_button]
        self.bbox = ipywidgets.HBox(children=children)
        children = [self.ftabs, self.bbox]
        self._file_picker_tabs = ipywidgets.Box(children=children)

        # Define the plot controls, start with 1 (self._subplots default)
        self.plot_controls = [PlotControl()]
        pcc_children = [pc.box for pc in self.plot_controls]
        self._plot_control_container = ipywidgets.Tab(children=pcc_children)
        self._plot_control_container.set_title(0, 'Plot Axes 0')

        # Define an Accordian for files, subplots and plots
        acc_children = [self._file_picker_tabs, self._subplots,
                        self._plot_control_container]
        self._accord = ipywidgets.Accordion(children=acc_children)
        self._accord.set_title(0, 'Files')
        self._accord.set_title(1, 'SubPlots')
        self._accord.set_title(2, 'Plots')

        # Initialise cubes container
        self._cubes = []

        # Display the browse interface.
        IPython.display.display(self._accord)
        IPython.display.display(self._plot_button)
        IPython.display.display(self._plot_container)
项目:pyTSEB    作者:hectornieto    | 项目源码 | 文件源码
def define_site_description_image(self):
        '''Widgets for site description parameters'''

        self.w_latBut = widgets.Button(description='Browse Latitude Image')
        self.w_lat = widgets.Text(
            description='(Decimal degrees)', value='0', width=500)
        self.w_lonBut = widgets.Button(description='Browse Longitude Image')
        self.w_lon = widgets.Text(
            description='(Decimal degrees):', value='0', width=500)
        self.w_altBut = widgets.Button(description='Browse Altitude Image')
        self.w_alt = widgets.Text(
            description='(m):', value='0', width=500)
        self.w_stdlon_But = widgets.Button(description='Browse Standard Longitude Image')
        self.w_stdlon = widgets.Text(
            description='(Decimal degrees):', value='0', width=500)
        self.w_z_u_But = widgets.Button(description='Wind meas. height')
        self.w_z_u = widgets.Text(
            description='(m):', value=str(self.zu), width=500)
        self.w_z_T_But = widgets.Button(description='Air temp. meas. height')
        self.w_z_T = widgets.Text(
            description='(m):', value=str(self.zt), width=500)

        self.site_page = widgets.VBox([widgets.HTML('Select latitude image or type a constant value'),
                                      widgets.HBox([self.w_latBut, self.w_lat]),
                                      widgets.HTML('Select longitude image or type a constant value'),
                                      widgets.HBox([self.w_lonBut, self.w_lon]),
                                      widgets.HTML('Select altitude image or type a constant value'),
                                      widgets.HBox([self.w_altBut, self.w_alt]),
                                      widgets.HTML('Select standard longitude image or type a constant value'),
                                      widgets.HBox([self.w_stdlon_But, self.w_stdlon]),
                                      widgets.HTML('Select wind measurement height image or type a constant value'),
                                      widgets.HBox([self.w_z_u_But, self.w_z_u]),
                                      widgets.HTML('Select air temperature measurement height image or type a constant value'),
                                      widgets.HBox([self.w_z_T_But, self.w_z_T])])

        self.w_latBut.on_click(
            lambda b: self._on_input_clicked(b, 'Latitude', self.w_lat))
        self.w_lonBut.on_click(
            lambda b: self._on_input_clicked(b, 'Longitude', self.w_lon))
        self.w_altBut.on_click(
            lambda b: self._on_input_clicked(b, 'Altitude', self.w_alt))
        self.w_stdlon_But.on_click(
            lambda b: self._on_input_clicked(b, 'Standard Longitude', self.w_stdlon))
        self.w_z_u_But.on_click(
            lambda b: self._on_input_clicked(b, 'Wind Measurement Height', self.w_z_u))
        self.w_z_T_But.on_click(
            lambda b: self._on_input_clicked(b, 'Air Temperature Measurement Height', self.w_z_T))
项目:pyTSEB    作者:hectornieto    | 项目源码 | 文件源码
def surface_properties_image(self):
        '''Widgets for canopy properties'''

        self.w_PT_But = widgets.Button(
            description='Browse Initial alphaPT Image')
        self.w_PT = widgets.Text(description=' ', value=str(self.max_PT), width=500)        
        self.w_LAD_But = widgets.Button(
            description='Browse Leaf Angle Distribution Image')
        self.w_LAD = widgets.Text(description='(degrees)', value=str(self.x_LAD), width=500)        
        self.w_leafwidth_But = widgets.Button(
            description='Browse Leaf Width Image')
        self.w_leafwidth = widgets.Text(description='(m)', value=str(self.leaf_width), width=500)
        self.w_zsoil_But = widgets.Button(
            description='Browse Soil Roughness Image')
        self.w_zsoil = widgets.Text(description='(m)', value=str(self.z0soil), width=500)        
        self.w_lc_But = widgets.Button(
            description='Browse Land Cover Image')
        # Landcover classes and values come from IGBP Land Cover Type Classification
        self.w_lc = widgets.Dropdown(
            options={
                'CROP': 12,
                'GRASS': 10,
                'SHRUB': 6,
                'CONIFER': 1,
                'BROADLEAVED': 4},
            value=self.landcover,
            description=" ",
            width=300)
        lcText = widgets.HTML(value='''Land cover information is used to estimate roughness. <BR>
                                    For shrubs, conifers and broadleaves we use the model of <BR>
                                    Schaudt & Dickinson (2000) Agricultural and Forest Meteorology. <BR>
                                    For crops and grasses we use a fixed ratio of canopy height<BR>''', width=600)

        self.calc_row_options()
        self.veg_page = widgets.VBox([widgets.HTML('Select alphaPT image or type a constant value'),
                                      widgets.HBox([self.w_PT_But, self.w_PT]),
                                      widgets.HTML('Select leaf angle distribution image or type a constant value'),
                                      widgets.HBox([self.w_LAD_But, self.w_LAD]),
                                      widgets.HTML('Select leaf width image or type a constant value'),
                                      widgets.HBox([self.w_leafwidth_But, self.w_leafwidth]),
                                      widgets.HTML('Select soil roughness image or type a constant value'),
                                      widgets.HBox([self.w_zsoil_But, self.w_zsoil]),
                                      widgets.HTML('Select landcover image or type a constant value'),
                                      widgets.HBox([self.w_lc_But, self.w_lc]),
                                      lcText,
                                      widgets.HBox([self.w_row, self.w_rowaz])], background_color='#EEE')

        self.w_PT_But.on_click(
            lambda b: self._on_input_clicked(b, 'Initial alphaPT', self.w_PT))
        self.w_LAD_But.on_click(
            lambda b: self._on_input_clicked(b, 'Leaf Angle Distribution', self.w_LAD))
        self.w_leafwidth_But.on_click(
            lambda b: self._on_input_clicked(b, 'Leaf Width', self.w_leafwidth))
        self.w_zsoil_But.on_click(
            lambda b: self._on_input_clicked(b, 'Soil Roughness', self.w_zsoil))
        self.w_lc_But.on_click(
            lambda b: self._input_dropdown_clicked(b, 'Land Cover', self.w_lc))
项目:pyTSEB    作者:hectornieto    | 项目源码 | 文件源码
def resistances_image(self):
        '''Widgets for resistance model selection'''

        self.w_res = widgets.ToggleButtons(
            description='Select TSEB model to run:',
            options={
                'Kustas & Norman 1999': 0,
                'Choudhury & Monteith 1988': 1,
                'McNaughton & Van der Hurk': 2},
            value=self.res,
            width=300)

        self.w_PT_But = widgets.Button(
            description='Browse Initial alphaPT Image')
        self.w_PT = widgets.Text(description=' ', value=str(self.max_PT), width=500)            

        self.w_KN_b_But = widgets.Button(
            description = 'Browse Resistance Parameter b Image')
        self.w_KN_b = widgets.Text(
            value=str(self.KN_b), description=' ', width=500)
        self.w_KN_c_But = widgets.Button(
            description = ('Browse Resistance Parameter c image'))
        self.w_KN_c = widgets.Text(
            value=str(self.KN_c), description='(m s-1 K-1/3)', width=500)
        self.w_KN_C_dash_But = widgets.Button(
            description = ("Browse Resistance Parameter C' Image"))
        self.w_KN_C_dash = widgets.Text(
            value=str(self.KN_C_dash), description="s1/2 m-1", width=500)
        self.KN_params_box =  widgets.VBox([widgets.HTML('Select resistance parameter b image or type a constant value'),
                                            widgets.HBox([self.w_KN_b_But, self.w_KN_b]),
                                            widgets.HTML('Select resistance parameter c image or type a constant value'),
                                            widgets.HBox([self.w_KN_c_But, self.w_KN_c]),
                                            widgets.HTML('Select resistance parameter C\' image or type a constant value'),
                                            widgets.HBox([self.w_KN_C_dash_But, self.w_KN_C_dash])], background_color='#EEE')
        self.res_page = widgets.VBox([self.w_res, self.KN_params_box], background_color='#EEE')

        self.w_KN_b_But.on_click(
            lambda b: self._on_input_clicked(b, 'Resistance Parameter b', self.w_KN_b))
        self.w_KN_c_But.on_click(
            lambda b: self._on_input_clicked(b, 'Resistance Parameter c', self.w_KN_c))
        self.w_KN_C_dash_But.on_click(
            lambda b: self._on_input_clicked(b, 'Resistance Parameter C\'', self.w_KN_C_dash))
项目:notebook-molecular-visualization    作者:Autodesk    | 项目源码 | 文件源码
def _make_ui_pane(self, hostheight):
        layout = ipy.Layout(width='325px',
                            height=str(int(hostheight.rstrip('px')) - 50) + 'px')
        #element_height = str(int(hostheight.rstrip('px')) - 125) + 'px'
        element_height = None
        # NOTE - element_height was used for the listbox-style orblist.
        #   HOWEVER ipywidgets 6.0 only displays those as a dropdown.
        #   This is therefore disabled until we can display listboxes again. -- AMV 7/16

        # Orbital set selector
        self.status_element = ipy.HTML(layout=ipy.Layout(width='inherit', height='20px'))
        orbtype_label = ipy.Label("Orbital set:")
        self.type_dropdown = ipy.Dropdown(options=list(self.wfn.orbitals.keys()))
        initialtype = 'canonical'
        if initialtype not in self.type_dropdown.options:
            initialtype = next(iter(self.type_dropdown.options.keys()))
        self.type_dropdown.value = initialtype
        self.type_dropdown.observe(self.new_orb_type, 'value')

        # List of orbitals in this set
        orblist_label = ipy.Label("Orbital:")
        self.orblist = ipy.Dropdown(options={None: None},
                                    layout=ipy.Layout(width=layout.width, height=element_height))
        traitlets.link((self.orblist, 'value'), (self, 'current_orbital'))

        # Isovalue selector
        isoval_label = ipy.Label('Isovalue:')
        self.isoval_selector = ipy.FloatSlider(min=0.0, max=0.075,
                                               value=0.01, step=0.00075,
                                               readout_format='.4f',
                                               layout=ipy.Layout(width=layout.width))
        traitlets.link((self.isoval_selector, 'value'), (self, 'isoval'))

        # Opacity selector
        opacity_label = ipy.Label('Opacity:')
        self.opacity_selector = ipy.FloatSlider(min=0.0, max=1.0,
                                               value=0.8, step=0.01,
                                               readout_format='.2f',
                                               layout=ipy.Layout(width=layout.width))
        traitlets.link((self.opacity_selector, 'value'), (self, 'orb_opacity'))

        # Resolution selector
        resolution_label = ipy.Label("Grid resolution:", layout=ipy.Layout(width=layout.width))
        self.orb_resolution = ipy.Text(layout=ipy.Layout(width='75px',
                                                         positioning='bottom'))
        self.orb_resolution.value = str(self.numpoints)
        self.resolution_button = ipy.Button(description='Update resolution')
        self.resolution_button.on_click(self.change_resolution)
        traitlets.directional_link((self, 'numpoints'), (self.orb_resolution, 'value'),
                                   transform=str)

        self.uipane = ipy.VBox([self.status_element,
                                orbtype_label, self.type_dropdown,
                                orblist_label, self.orblist,
                                isoval_label, self.isoval_selector,
                                opacity_label, self.opacity_selector,
                                resolution_label, self.orb_resolution, self.resolution_button])
        self.new_orb_type()
        self.type_dropdown.observe(self.new_orb_type, 'value')
        return self.uipane
项目:notebook-molecular-visualization    作者:Autodesk    | 项目源码 | 文件源码
def __init__(self, xface):
        self.xface = xface
        if self.xface.is_installed():
            version_string = xface.installed_version()
            if not version_string:
                version_string = 'unknown'

            if version_string != xface.expectedversion:
                version_string = '<span style="color:red">%s</span>' % version_string

        self.maintext = ipy.HTML(
                ('<span class="nbv-table-row nbv-width-med nbv-monospace">'
                 '           {xface.packagename}</span> '
                 '<span class="nbv-table-row nbv-monospace nbv-width-sm">'
                 '                {localversion}</span> '
                 '<span class="nbv-table-row nbv-monospace nbv-width-sm">'
                 '                {xface.expectedversion}</span>'
                 '<span class="nbv-width-sm nbv-table-row">&nbsp;</span>'  # empty space
                 ).format(xface=xface,
                            localversion=(version_string if self.xface.is_installed()
                                                          else MISSING)))

        if xface.required:
            self.selector = ipy.ToggleButtons(options=['locally'])
        elif not xface.is_installed():
            self.selector = ipy.ToggleButtons(options=['in docker'],
                                              button_style='warning')
        else:
            self.selector = ipy.ToggleButtons(options=['locally', 'in docker'],
                                              value='in docker' if xface.force_remote else 'locally',
                                              button_style='info')
            self.selector.observe(self._toggle, 'value')

        self.selector.add_class('nbv-width-lg')
        self.selector.add_class("nbv-table-row")

        children = [self.maintext, self.selector]

        if not self.xface.required and self.xface.is_installed():
            self.save_button = ipy.Button(description='Make default')
            self.save_button.on_click(self.save_selection)
            self.save_button.add_class('nbv-table-row')
            children.append(self.save_button)

        super().__init__(children=children,
                         layout=ipy.Layout(width='100%', align_items='flex-end'))
项目:notebook-molecular-visualization    作者:Autodesk    | 项目源码 | 文件源码
def __init__(self, paramdef):
        super(ParamSelector, self).__init__(layout=ipy.Layout(display='flex',
                                                              flex_flow='nowrap',
                                                              align_content='stretch'))

        self.paramdef = paramdef

        children = []
        self.name = ipy.HTML("<p style='text-align:right'>%s:</p>" % paramdef.displayname,
                             layout=ipy.Layout(width='200px'))
        children.append(self.name)

        if paramdef.choices:
            self.selector = ipy.Dropdown(options=paramdef.choices, **self.WIDGETKWARGS)
        elif paramdef.type == bool:
            self.selector = ipy.ToggleButtons(options=[True, False], **self.WIDGETKWARGS)
        elif paramdef.units:
            self.selector = UnitText(units=paramdef.units, **self.WIDGETKWARGS)
        elif paramdef.type == float:
            self.selector = ipy.FloatText(**self.WIDGETKWARGS)
        elif paramdef.type == int:
            self.selector = ipy.IntText(**self.WIDGETKWARGS)
        elif paramdef.type == str:
            self.selector = ipy.Text(**self.WIDGETKWARGS)
        else:
            self.selector = ReadOnlyRepr(**self.WIDGETKWARGS)
        children.append(self.selector)

        children = [self.name, self.selector]

        self.default_button = None
        if paramdef.default:
            self.default_button = ipy.Button(description='Default',
                                             tooltip='Set to default: %s' % self.paramdef.default,
                                             layout=ipy.Layout(width='75px'))
            self.default_button.on_click(self.default)
            children.append(self.default_button)
            self.default()

        self.help_link = None
        if paramdef.help_url:
            self.help_link = ipy.HTML('<a href="%s" target="_blank">?</a>' % paramdef.help_url)
            children.append(self.help_link)

        self.children = children
项目:notebook-molecular-visualization    作者:Autodesk    | 项目源码 | 文件源码
def __init__(self, mol):
        self._current_shapes = []
        self.mol = mol
        self.tolerance = 0.3 * u.angstrom
        self.original_coords = mol.positions.copy()

        self.showing = ipy.HTML()
        self.viewer = mol.draw3d(width='650px')
        """:type viewer: moldesign.viewer.GeometryViewer"""

        self.description = ipy.HTML()
        self.symm_selector = ipy.Select()
        self.symm_selector.observe(self.show_symmetry, names='value')

        self.apply_button = ipy.Button(description='Symmetrize')
        self.apply_button.on_click(self.apply_selected_symmetry)

        self.reset_button = ipy.Button(description='Reset')
        self.reset_button.on_click(self.reset_coords)

        self.apply_all_button = ipy.Button(description='Apply all',
                                           layout=ipy.Layout(padding='10px'))
        self.apply_all_button.on_click(self.set_highest_symmetry)

        self.tolerance_descrip = ipy.HTML(u'<small>tolerance/\u212B</small>',)
        self.tolerance_chooser = ipy.BoundedFloatText(value=self.tolerance.value_in(u.angstrom),
                                                      min=0.0)

        self.recalculate_button = ipy.Button(description='Recalculate')
        self.recalculate_button.on_click(self.coords_changed)

        self.symm_pane = VBox([self.description,
                               self.symm_selector,
                               HBox([self.apply_button, self.reset_button]),
                               self.apply_all_button,
                               HBox([self.tolerance_chooser, self.recalculate_button]),
                               self.tolerance_descrip],
                              layout=ipy.Layout(width='325px'))

        self.symmetry = None
        self.coords_changed()

        self.hbox = HBox([VBox([self.viewer, self.showing]), self.symm_pane])
        super().__init__([self.hbox])
项目:paramnb    作者:ioam    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        # Compute selected and unselected values
        options = kwargs.get('options', {})
        if isinstance(options, list):
            options = named_objs([(opt, opt) for opt in options])
        self._reverse_lookup = {v: k for k, v in options.items()}
        selected = [self._reverse_lookup[v] for v in kwargs.get('value', [])]
        unselected = [k for k in options if k not in selected]

        # Define whitelist and blacklist
        self._lists = {False: SelectMultiple(options=unselected),
                       True: SelectMultiple(options=selected)}

        self._lists[False].observe(self._update_selection, 'value')
        self._lists[True].observe(self._update_selection, 'value')

        # Define buttons
        button_layout = Layout(width='50px')
        self._buttons = {False: Button(description='<<', layout=button_layout),
                         True: Button(description='>>', layout=button_layout)}
        self._buttons[False].on_click(self._apply_selection)
        self._buttons[True].on_click(self._apply_selection)

        # Define search
        self._search = {False: Text(placeholder='Filter available options'),
                        True: Text(placeholder='Filter selected options')}
        self._search[False].observe(self._filter_options, 'value')
        self._search[True].observe(self._filter_options, 'value')

        # Define Layout
        no_margin = Layout(margin='0')
        row_layout = Layout(margin='0', display='flex', justify_content='space-between')

        search_row = HBox([self._search[False], self._search[True]])
        search_row.layout = row_layout
        button_box = VBox([self._buttons[True], self._buttons[False]],
                          layout=Layout(margin='auto 0'))
        tab_row = HBox([self._lists[False], button_box, self._lists[True]])
        tab_row.layout = row_layout
        self._composite = VBox([search_row, tab_row], layout=no_margin)

        self.observe(self._update_options, 'options')
        self.observe(self._update_value, 'value')

        self._selected = {False: [], True: []}
        self._query = {False: '', True: ''}
        super(CrossSelect, self).__init__(*args, **dict(kwargs, options=options))