【问题标题】:Ignore matplotlib cursor widget when toolbar widget selected?选择工具栏小部件时忽略 matplotlib 光标小部件?
【发布时间】:2014-01-09 18:14:23
【问题描述】:

我在交互式 Matplotlib 图中使用光标小部件,如下所示:

cursor = Cursor(ax1, useblit=True, color='red', linewidth=1)
cid = fig.canvas.mpl_connect('button_press_event', on_click)

效果很好。 on_click 函数采用 x,y 点击位置并进行一些补充绘图。基本的东西。

当我激活缩放工具时,我也在捕捉点击。是否有必要像 RectangleSelector 示例那样将激活和停用击键绑定到小部件,或者是否存在知道工具栏项状态的方法?

从 RectangleSelector 示例中打开/关闭选择器的示例:

def toggle_selector(event):
    if event.key in ['Q','q'] and toggle_selector.RS.active:
        toggle_selector.RS.set_active(False)
    if event.key in ['A', 'a'] and not toggle_selector.RS.active:
        toggle_selector.RS.set_active(True)

【问题讨论】:

    标签: python matplotlib interactive


    【解决方案1】:

    由于this commitaccepted answer 不再适用于 matplotlib 3.3 版。使用标准 NavigationToolbar2 时,您可以改用其 mode 属性。

    类似于ImportanceOfBeingErnest's answer的例子:

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    
    def on_click(evt):
        state = fig.canvas.manager.toolbar.mode
        if state == '':
            print("no tool selected")
        else:
            print(f"{state} selected")
    
    cid = fig.canvas.mpl_connect('button_press_event', on_click)
    
    plt.show()
    

    【讨论】:

      【解决方案2】:

      由于toolmanager 工具栏现在可用于更多后端,它可能在这里有用。

      import matplotlib.pyplot as plt
      plt.rcParams['toolbar'] = 'toolmanager'
      
      fig, ax = plt.subplots()
      
      def on_click(evt):
          state = fig.canvas.manager.toolbar.toolmanager.active_toggle["default"]
          if state is None:
              print("no tool selected")
          else:
              print(f"{state} selected")
      
      cid = fig.canvas.mpl_connect('button_press_event', on_click)
      
      plt.show()
      

      【讨论】:

        【解决方案3】:

        这不是公共状态,但你可以检查

        fig.canvas.manager.toolbar._active is None
        

        如果工具栏不尝试抓取点击(通过平移或缩放),则为 True

        您正在触及并触及随时可能发生变化的内部状态,因此使用此操作需您自担风险。对于以_* 开头且没有弃用期的任何内容的更改,开发人员不会感到内疚。

        【讨论】:

        • 谢谢。检查if fig.canvas.manager.toolbar._active is not None: ignore_custom_cursor_clicks。随着 Matplotlib 增加交互性,是否有可能提供公共访问权限?
        • 其实现在正在推动重新编写工具栏。您应该创建一个我在 github 上要求的问题。在文本中包含@tacaswell,这样我就会被 ping 通
        • 自 2013 年的问题以来,有任何关于此的公共方法的更新吗?
        • 有一个草稿版本的新工具栏随 1.5 一起发布,但它只支持 gtk。正在审查中对 GUI 类进行了重大重写,这阻碍了在其他后端构建新工具栏。审查 GUI 更改是 2.1 的优先事项(2016 年夏末/初秋)
        • matplotlib 3.3 及以上版本见this answer
        猜你喜欢
        • 2015-03-30
        • 1970-01-01
        • 1970-01-01
        • 2013-09-03
        • 2019-06-14
        • 1970-01-01
        • 2021-11-05
        • 1970-01-01
        • 2023-04-05
        相关资源
        最近更新 更多