當前位置: 首頁>>代碼示例>>Python>>正文


Python ipywidgets.CallbackDispatcher類代碼示例

本文整理匯總了Python中ipywidgets.CallbackDispatcher的典型用法代碼示例。如果您正苦於以下問題:Python CallbackDispatcher類的具體用法?Python CallbackDispatcher怎麽用?Python CallbackDispatcher使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了CallbackDispatcher類的8個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __init__

 def __init__(self, **kwargs):
     super(Mark, self).__init__(**kwargs)
     self._hover_handlers = CallbackDispatcher()
     self._click_handlers = CallbackDispatcher()
     self._legend_click_handlers = CallbackDispatcher()
     self._legend_hover_handlers = CallbackDispatcher()
     self._element_click_handlers = CallbackDispatcher()
     self._bg_click_handlers = CallbackDispatcher()
     self.on_msg(self._handle_custom_msgs)
開發者ID:ivanov,項目名稱:bqplot,代碼行數:9,代碼來源:marks.py

示例2: Mark


#.........這裏部分代碼省略.........
    tooltip = Instance(DOMWidget, allow_none=True, default_value=None).tag(sync=True, **widget_serialization)
    tooltip_style = Dict({'opacity': 0.9}).tag(sync=True)
    interactions = Dict({'hover': 'tooltip'}).tag(sync=True)
    tooltip_location = Enum(['mouse', 'center'], default_value='mouse').tag(sync=True)

    _model_name = Unicode('MarkModel').tag(sync=True)
    _model_module = Unicode('bqplot').tag(sync=True)
    _view_module = Unicode('bqplot').tag(sync=True)
    _ipython_display_ = None

    def _get_dimension_scales(self, dimension, preserve_domain=False):
        """
        Return the list of scales corresponding to a given dimension.

        The preserve_domain optional argument specifies whether one should
        filter out the scales for which preserve_domain is set to True.
        """
        if preserve_domain:
            return [
                self.scales[k] for k in self.scales if (
                    k in self.scales_metadata
                    and self.scales_metadata[k].get('dimension') == dimension
                    and not self.preserve_domain.get(k)
                )
            ]
        else:
            return [
                self.scales[k] for k in self.scales if (
                    k in self.scales_metadata
                    and self.scales_metadata[k].get('dimension') == dimension
                )
            ]

    def _scales_validate(self, scales, scales_trait):
        """
        Validates the `scales` based on the mark's scaled attributes metadata.

        First checks for missing scale and then for 'rtype' compatibility.
        """
        # Validate scales' 'rtype' versus data attribute 'rtype' decoration
        # At this stage it is already validated that all values in self.scales
        # are instances of Scale.
        for name in self.trait_names(scaled=True):
            trait = self.traits()[name]
            if name not in scales:
                # Check for missing scale
                if not trait.allow_none:
                    raise TraitError("Missing scale for data attribute %s." %
                                     name)
            else:
                # Check scale range type compatibility
                if scales[name].rtype != trait.get_metadata('rtype'):
                    raise TraitError("Range type mismatch for scale %s." %
                                     name)
        return scales

    def _selected_default(self):
        return None

    def __init__(self, **kwargs):
        super(Mark, self).__init__(**kwargs)
        self._hover_handlers = CallbackDispatcher()
        self._click_handlers = CallbackDispatcher()
        self._legend_click_handlers = CallbackDispatcher()
        self._legend_hover_handlers = CallbackDispatcher()
        self._element_click_handlers = CallbackDispatcher()
        self._bg_click_handlers = CallbackDispatcher()
        self.on_msg(self._handle_custom_msgs)

    def on_hover(self, callback, remove=False):
        self._hover_handlers.register_callback(callback, remove=remove)

    def on_click(self, callback, remove=False):
        self._click_handlers.register_callback(callback, remove=remove)

    def on_legend_click(self, callback, remove=False):
        self._legend_click_handlers.register_callback(callback, remove=remove)

    def on_legend_hover(self, callback, remove=False):
        self._legend_hover_handlers.register_callback(callback, remove=remove)

    def on_element_click(self, callback, remove=False):
        self._element_click_handlers.register_callback(callback, remove=remove)

    def on_background_click(self, callback, remove=False):
        self._bg_click_handlers.register_callback(callback, remove=remove)

    def _handle_custom_msgs(self, _, content, buffers=None):
        if content.get('event', '') == 'hover':
            self._hover_handlers(self, content)
        if content.get('event', '') == 'click':
            self._click_handlers(self, content)
        elif content.get('event', '') == 'legend_click':
            self._legend_click_handlers(self, content)
        elif content.get('event', '') == 'legend_hover':
            self._legend_hover_handlers(self, content)
        elif content.get('event', '') == 'element_click':
            self._element_click_handlers(self, content)
        elif content.get('event', '') == 'background_click':
            self._bg_click_handlers(self, content)
開發者ID:ivanov,項目名稱:bqplot,代碼行數:101,代碼來源:marks.py

示例3: Scatter


#.........這裏部分代碼省略.........
        orientation of the markers representing the data points.
        The rotation scale's range is [0, 180]
        Defaults to 0 when not provided or when a value is NaN.

    Notes
    -----
    The fields which can be passed to the default tooltip are:
        All the data attributes
        index: index of the marker being hovered on
    The following are the events which can trigger interactions:
        click: left click of the mouse
        hover: mouse-over an element
    The following are the interactions which can be linked to the above events:
        tooltip: display tooltip
        add: add new points to the scatter (can only linked to click)
    """
    # Mark decoration
    icon = 'fa-cloud'
    name = 'Scatter'

    # Scaled attribtes
    x = NdArray().tag(sync=True, min_dim=1, max_dim=1, scaled=True,
                rtype='Number', atype='bqplot.Axis')
    y = NdArray().tag(sync=True, min_dim=1, max_dim=1,
                scaled=True, rtype='Number', atype='bqplot.Axis')
    color = NdArray(None, allow_none=True).tag(sync=True, scaled=True,
                    rtype='Color', atype='bqplot.ColorAxis', min_dim=1, max_dim=1)
    opacity = NdArray(None, allow_none=True).tag(sync=True, scaled=True,
                      rtype='Number', min_dim=1, max_dim=1)
    size = NdArray(None, allow_none=True).tag(sync=True, scaled=True,
                   rtype='Number', min_dim=1, max_dim=1)
    skew = NdArray(None, allow_none=True).tag(sync=True, scaled=True, rtype='Number',
                   min_dim=1, max_dim=1)
    rotation = NdArray(None, allow_none=True).tag(sync=True, scaled=True,
                       rtype='Number', min_dim=1, max_dim=1)
    hovered_style = Dict().tag(sync=True)
    unhovered_style = Dict().tag(sync=True)
    hovered_point = Int(None, allow_none=True).tag(sync=True)

    # Other attributes
    scales_metadata = Dict({
        'x': {'orientation': 'horizontal', 'dimension': 'x'},
        'y': {'orientation': 'vertical', 'dimension': 'y'},
        'color': {'dimension': 'color'},
        'size': {'dimension': 'size'},
        'opacity': {'dimension': 'opacity'}
    }).tag(sync=True)
    marker = Enum(['circle', 'cross', 'diamond', 'square', 'triangle-down',
                   'triangle-up', 'arrow', 'rectangle', 'ellipse'],
                  default_value='circle').tag(sync=True, display_name='Marker')
    default_colors = List(trait=Color(default_value=None, allow_none=True),
                          default_value=['DeepSkyBlue']).tag(sync=True,
                          display_name='Colors')
    stroke = Color(None, allow_none=True).tag(sync=True, display_name='Stroke color')
    stroke_width = Float(1.5).tag(sync=True, display_name='Stroke width')
    default_opacities = List(trait=Float(1.0, min=0, max=1, allow_none=True)).tag(sync=True, display_name='Opacities')
    default_skew = Float(0.5, min=0, max=1).tag(sync=True)
    default_size = Int(64).tag(sync=True, display_name='Default size')

    names = NdArray().tag(sync=True)
    display_names = Bool(True).tag(sync=True, display_name='Display names')
    fill = Bool(True).tag(sync=True)
    drag_color = Color(None, allow_none=True).tag(sync=True)
    names_unique = Bool(True).tag(sync=True)

    enable_move = Bool().tag(sync=True)
    enable_delete = Bool().tag(sync=True)
    restrict_x = Bool().tag(sync=True)
    restrict_y = Bool().tag(sync=True)
    update_on_move = Bool().tag(sync=True)

    def __init__(self, **kwargs):
        self._drag_start_handlers = CallbackDispatcher()
        self._drag_handlers = CallbackDispatcher()
        self._drag_end_handlers = CallbackDispatcher()
        super(Scatter, self).__init__(**kwargs)

    def on_drag_start(self, callback, remove=False):
        self._drag_start_handlers.register_callback(callback, remove=remove)

    def on_drag(self, callback, remove=False):
        self._drag_handlers.register_callback(callback, remove=remove)

    def on_drag_end(self, callback, remove=False):
        self._drag_end_handlers.register_callback(callback, remove=remove)

    def _handle_custom_msgs(self, _, content, buffers=None):
        event = content.get('event', '')

        if event == 'drag_start':
            self._drag_start_handlers(self, content)
        elif event == 'drag':
            self._drag_handlers(self, content)
        elif event == 'drag_end':
            self._drag_end_handlers(self, content)

        super(Scatter, self)._handle_custom_msgs(self, content)

    _view_name = Unicode('Scatter').tag(sync=True)
    _model_name = Unicode('ScatterModel').tag(sync=True)
開發者ID:ivanov,項目名稱:bqplot,代碼行數:101,代碼來源:marks.py

示例4: MarketMap


#.........這裏部分代碼省略.........
        stroke for the cell being hovered on
    font_style: dict
        CSS style for the text of each cell

    Other Attributes

    enable_select: bool
        boolean to control the ability to select the cells of the map by
        clicking
    enable_hover: bool
        boolean to control if the map should be aware of which cell is being
        hovered on. If it is set to False, tooltip will not be displayed

    Note
    ----

    The aspect ratios stand for width / height ratios.

     - If the available space is within bounds in terms of min and max aspect
       ratio, we use the entire available space.
     - If the available space is too oblong horizontally, we use the client
       height and the width that corresponds max_aspect_ratio (maximize width
       under the constraints).
     - If the available space is too oblong vertically, we use the client width
       and the height that corresponds to min_aspect_ratio (maximize height
       under the constraint).
       This corresponds to maximizing the area under the constraints.

    Default min and max aspect ratio are both equal to 16 / 9.
    """
    names = Array([]).tag(sync=True, **array_serialization)
    groups = Array([]).tag(sync=True, **array_serialization)
    display_text = Array(None, allow_none=True)\
        .tag(sync=True, **array_serialization)
    ref_data = DataFrame(None, allow_none=True)\
        .tag(sync=True, **dataframe_serialization)\
        .valid(dataframe_warn_indexname)
    title = Unicode().tag(sync=True)

    tooltip_fields = List().tag(sync=True)
    tooltip_formats = List().tag(sync=True)
    show_groups = Bool().tag(sync=True)

    cols = Int(allow_none=True).tag(sync=True)
    rows = Int(allow_none=True).tag(sync=True)

    row_groups = Int(1).tag(sync=True)
    colors = List(CATEGORY10).tag(sync=True)
    scales = Dict().tag(sync=True, **widget_serialization)
    axes = List().tag(sync=True, **widget_serialization)
    color = Array([]).tag(sync=True, **array_serialization)
    map_margin = Dict(dict(top=50, right=50, left=50, bottom=50))\
        .tag(sync=True)

    layout = LayoutTraitType(kw=dict(min_width='125px'))\
        .tag(sync=True, **widget_serialization)
    min_aspect_ratio = Float(1.0).tag(sync=True)
    # Max aspect ratio is such that we can have 3 charts stacked vertically
    # on a 16:9 monitor: 16/9*3 ~ 5.333
    max_aspect_ratio = Float(6.0).tag(sync=True)

    stroke = Color('white').tag(sync=True)
    group_stroke = Color('black').tag(sync=True)
    selected_stroke = Color('dodgerblue', allow_none=True).tag(sync=True)
    hovered_stroke = Color('orangered', allow_none=True).tag(sync=True)
    font_style = Dict().tag(sync=True)
    title_style = Dict().tag(sync=True)

    selected = List().tag(sync=True)
    enable_hover = Bool(True).tag(sync=True)
    enable_select = Bool(True).tag(sync=True)
    tooltip_widget = Instance(DOMWidget, allow_none=True, default_value=None)\
        .tag(sync=True, **widget_serialization)

    def __init__(self, **kwargs):
        super(MarketMap, self).__init__(**kwargs)
        self._hover_handlers = CallbackDispatcher()
        self.on_msg(self._handle_custom_msgs)

    def on_hover(self, callback, remove=False):
        self._hover_handlers.register_callback(callback, remove=remove)

    def _handle_custom_msgs(self, _, content, buffers=None):
        if content.get('event', '') == 'hover':
            self._hover_handlers(self, content)

    def _compare(self, a, b):
        # Compare dataframes properly
        import pandas as pd
        if isinstance(a, pd.DataFrame) or isinstance(b, pd.DataFrame):
            return pd.DataFrame.equals(a, b)

        return super(MarketMap, self)._compare(a, b)

    _view_name = Unicode('MarketMap').tag(sync=True)
    _model_name = Unicode('MarketMapModel').tag(sync=True)
    _view_module = Unicode('bqplot').tag(sync=True)
    _model_module = Unicode('bqplot').tag(sync=True)
    _view_module_version = Unicode(__frontend_version__).tag(sync=True)
    _model_module_version = Unicode(__frontend_version__).tag(sync=True)
開發者ID:mwcraig,項目名稱:bqplot,代碼行數:101,代碼來源:market_map.py

示例5: __init__

 def __init__(self, **kwargs):
     super(MarketMap, self).__init__(**kwargs)
     self._hover_handlers = CallbackDispatcher()
     self.on_msg(self._handle_custom_msgs)
開發者ID:mwcraig,項目名稱:bqplot,代碼行數:4,代碼來源:market_map.py

示例6: __init__

 def __init__(self, **kwargs):
     super(Scatter, self).__init__(**kwargs)
     self._drag_end_handlers = CallbackDispatcher()
     self.on_msg(self._handle_custom_msgs)
開發者ID:raincoatrun,項目名稱:bqplot,代碼行數:4,代碼來源:marks.py

示例7: Scatter


#.........這裏部分代碼省略.........
    size: numpy.ndarray or None (default: [])
        size of the data points. Defaults to default_size when not provided or
        when a value is NaN
    skew: numpy.ndarray or None (default: [])
        skewness of the markers representing the data points. Defaults to
        default_skew when not provided or when a value is NaN
    rotation: numpy.ndarray or None (default: [])
        orientation of the markers representing the data points.
        The rotation scale's range is [0, 180]
        Defaults to 0 when not provided or when a value is NaN.

    Notes
    -----

    The fields which can be passed to the default tooltip are:
        All the data attributes
        index: index of the marker being hovered on
    The following are the events which can trigger interactions:
        click: left click of the mouse
        hover: mouse-over an element
    The following are the interactions which can be linked to the above events:
        tooltip: display tooltip
        add: add new points to the scatter (can only linked to click)
    """

    # Mark decoration
    icon = "fa-cloud"
    name = "Scatter"

    # Scaled attribtes
    x = NdArray(sync=True, min_dim=1, max_dim=1, scaled=True, rtype="Number", atype="bqplot.Axis")
    y = NdArray(sync=True, min_dim=1, max_dim=1, scaled=True, rtype="Number", atype="bqplot.Axis")
    color = NdArray(
        None, allow_none=True, sync=True, scaled=True, rtype="Color", atype="bqplot.ColorAxis", min_dim=1, max_dim=1
    )
    opacity = NdArray(None, allow_none=True, sync=True, scaled=True, rtype="Number", min_dim=1, max_dim=1)
    size = NdArray(None, allow_none=True, sync=True, scaled=True, rtype="Number", min_dim=1, max_dim=1)
    skew = NdArray(None, allow_none=True, sync=True, scaled=True, rtype="Number", min_dim=1, max_dim=1)
    rotation = NdArray(None, allow_none=True, sync=True, scaled=True, rtype="Number", min_dim=1, max_dim=1)

    # Other attributes
    scales_metadata = Dict(
        {
            "x": {"orientation": "horizontal", "dimension": "x"},
            "y": {"orientation": "vertical", "dimension": "y"},
            "color": {"dimension": "color"},
            "size": {"dimension": "size"},
            "opacity": {"dimension": "opacity"},
        },
        sync=True,
    )
    marker = Enum(
        ["circle", "cross", "diamond", "square", "triangle-down", "triangle-up", "arrow", "rectangle", "ellipse"],
        default_value="circle",
        sync=True,
        display_name="Marker",
    )
    default_colors = List(
        trait=Color(default_value=None, allow_none=True),
        default_value=["DeepSkyBlue"],
        sync=True,
        display_name="Colors",
    )
    stroke = Color(None, allow_none=True, sync=True, display_name="Stroke color")
    stroke_width = Float(1.5, sync=True, display_name="Stroke width")
    default_opacities = List(
        trait=Float(default_value=1.0, min=0, max=1, allow_none=True), sync=True, display_name="Opacities"
    )
    default_skew = Float(default_value=0.5, min=0, max=1, sync=True)
    default_size = Int(64, sync=True, display_name="Default size")

    names = NdArray(sync=True)
    display_names = Bool(True, sync=True, display_name="Display names")
    fill = Bool(True, sync=True)
    drag_color = Color(None, allow_none=True, sync=True)
    names_unique = Bool(True, sync=True)

    enable_move = Bool(False, sync=True)
    enable_delete = Bool(False, sync=True)
    restrict_x = Bool(False, sync=True)
    restrict_y = Bool(False, sync=True)
    update_on_move = Bool(False, sync=True)

    def __init__(self, **kwargs):
        super(Scatter, self).__init__(**kwargs)
        self._drag_end_handlers = CallbackDispatcher()
        self.on_msg(self._handle_custom_msgs)

    def on_drag_end(self, callback, remove=False):
        self._drag_end_handlers.register_callback(callback, remove=remove)

    def _handle_custom_msgs(self, _, content, buffers=None):
        super(Scatter, self)._handle_custom_msgs(self, content)
        if content.get("event", "") == "drag_end":
            self._drag_end_handlers(self, content)

    _view_name = Unicode("Scatter", sync=True)
    _view_module = Unicode("nbextensions/bqplot/Scatter", sync=True)
    _model_name = Unicode("ScatterModel", sync=True)
    _model_module = Unicode("nbextensions/bqplot/ScatterModel", sync=True)
開發者ID:raincoatrun,項目名稱:bqplot,代碼行數:101,代碼來源:marks.py

示例8: MarketMap


#.........這裏部分代碼省略.........
        minimum width of the entire map
    map_height: int
        minimum height of the entire map
    map_margin: dict
        margin for the market map plot area with respect to the entire display
        area
    preserve_aspect: bool
        boolean to control if the aspect ratio should be preserved or not
        during a resize
    cols: int
        Suggestion for no of columns in the map.If not specified, value is
        inferred from the no of rows and no of cells
    rows: int
        No of rows in the map.If not specified, value is inferred from the no
        of cells and no of columns.
        If both rows and columns are not specified, then a square is
        constructed basing on the no of cells.
        The above two attributes are suggestions which are respected unless
        they are not feasible. One required condition is that, the number of
        columns is odd when row_groups is greater than 1.
    row_groups: int
        No of groups the rows should be divided into. This can be used to draw
        more square cells for each of the groups

    Display Attributes
    ------------------
    colors: list of colors
        colors for each of the groups which are cycled over to cover all the
        groups
    stroke: color
        Stroke of each of the cells of the market map
    group_stroke: color
        Stroke of the border for the group of cells corresponding to a group
    selected_stroke: color
        stroke for the selected cells
    hovered_stroke: color
        stroke for the cell being hovered on

    Other Attributes
    ----------------
    enable_select: bool
        boolean to control the ability to select the cells of the map by
        clicking
    enable_hover: bool
        boolean to control if the map should be aware of which cell is being
        hovered on. If it is set to False, tooltip will not be displayed
    """
    map_width = Int(1080, sync=True)
    map_height = Int(800, sync=True)

    names = NdArray(sync=True)
    groups = NdArray(sync=True)
    display_text = NdArray(sync=True)
    ref_data = PandasDataFrame(sync=True)

    tooltip_fields = List(sync=True)
    tooltip_formats = List(sync=True)
    show_groups = Bool(False, sync=True)

    cols = Int(sync=True, allow_none=True)
    rows = Int(sync=True, allow_none=True)

    row_groups = Int(1, sync=True)
    colors = List(CATEGORY10, sync=True)
    scales = Dict(sync=True, allow_none=True,
                  **widget_serialization)
    axes = List(sync=True, allow_none=True,
                **widget_serialization)
    color = NdArray(sync=True)
    map_margin = Dict(dict(top=50, right=50, left=50, bottom=50), sync=True)
    preserve_aspect = Bool(False, sync=True,
                           display_name='Preserve aspect ratio')

    stroke = Unicode('white', sync=True)
    group_stroke = Unicode('black', sync=True)
    selected_stroke = Unicode('dodgerblue', sync=True)
    hovered_stroke = Unicode('orangered', sync=True)

    selected = List(sync=True)
    enable_hover = Bool(True, sync=True)
    enable_select = Bool(True, sync=True)
    tooltip_widget = Instance(DOMWidget, allow_none=True, sync=True,
                              **widget_serialization)

    def __init__(self, **kwargs):
        super(MarketMap, self).__init__(**kwargs)
        self._hover_handlers = CallbackDispatcher()
        self.on_msg(self._handle_custom_msgs)

    def on_hover(self, callback, remove=False):
        self._hover_handlers.register_callback(callback, remove=remove)

    def _handle_custom_msgs(self, _, content, buffers=None):
        if content.get('event', '') == 'hover':
            self._hover_handlers(self, content)

    _view_name = Unicode('MarketMap', sync=True)
    _view_module = Unicode('nbextensions/bqplot/MarketMap', sync=True)
    _model_name = Unicode('MarketMapModel', sync=True)
    _model_module = Unicode('nbextensions/bqplot/MarketMapModel', sync=True)
開發者ID:John-Keating,項目名稱:bqplot,代碼行數:101,代碼來源:market_map.py


注:本文中的ipywidgets.CallbackDispatcher類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。