返回介绍

在 traitsUI 中使用的 matplotlib 控件

发布于 2025-02-25 22:46:23 字数 2518 浏览 0 评论 0 收藏 0

相关文档:设计自己的 Trait 编辑器

在 traitsUI 所产生的界面中嵌入 matplotlib 的控件。

# -*- coding: utf-8 -*-
# file name: mpl_figure_editor.py
import wx
import matplotlib
# matplotlib 采用 WXAgg 为后台,这样才能将绘图控件嵌入以 wx 为后台界面库的 traitsUI 窗口中
matplotlib.use("WXAgg")
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wx import NavigationToolbar2Wx
from enthought.traits.ui.wx.editor import Editor
from enthought.traits.ui.basic_editor_factory import BasicEditorFactory

class _MPLFigureEditor(Editor):
  """
 相当于 wx 后台界面库中的编辑器,它负责创建真正的控件
 """
  scrollable = True

  def init(self, parent):
    self.control = self._create_canvas(parent)
    self.set_tooltip()
    print dir(self.item)

  def update_editor(self):
    pass

  def _create_canvas(self, parent):
    """
 创建一个 Panel, 布局采用垂直排列的 BoxSizer, panel 中中添加
 FigureCanvas, NavigationToolbar2Wx, StaticText 三个控件
 FigureCanvas 的鼠标移动事件调用 mousemoved 函数,在 StaticText
 显示鼠标所在的数据坐标
 """
    panel = wx.Panel(parent, -1, style=wx.CLIP_CHILDREN)
    def mousemoved(event):
      panel.info.SetLabel("%s, %s" % (event.xdata, event.ydata))    
    panel.mousemoved = mousemoved
    sizer = wx.BoxSizer(wx.VERTICAL)
    panel.SetSizer(sizer)
    mpl_control = FigureCanvas(panel, -1, self.value)
    mpl_control.mpl_connect("motion_notify_event", mousemoved)
    toolbar = NavigationToolbar2Wx(mpl_control)
    sizer.Add(mpl_control, 1, wx.LEFT | wx.TOP | wx.GROW)      
    sizer.Add(toolbar, 0, wx.EXPAND|wx.RIGHT)
    panel.info = wx.StaticText(parent, -1)
    sizer.Add(panel.info)

    self.value.canvas.SetMinSize((10,10))
    return panel

class MPLFigureEditor(BasicEditorFactory):
  """
 相当于 traits.ui 中的 EditorFactory,它返回真正创建控件的类
 """  
  klass = _MPLFigureEditor

if __name__ == "__main__":
  from matplotlib.figure import Figure  
  from enthought.traits.api import HasTraits, Instance
  from enthought.traits.ui.api import View, Item
  from numpy import sin, cos, linspace, pi

  class Test(HasTraits):
    figure = Instance(Figure, ())
    view = View(
      Item("figure", editor=MPLFigureEditor(), show_label=False),
      width = 400,
      height = 300,
      resizable = True)
    def __init__(self):
      super(Test, self).__init__()
      axes = self.figure.add_subplot(111)
      t = linspace(0, 2*pi, 200)
      axes.plot(sin(t))

  Test().configure_traits()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文