python之matplotlib学习(二)-与wxpython的交互


通过上面学习,知道python与matplotlib交互有三种方式,与GUI交互采用第三种方法面向对象法。 首先知道Matplotlib的常见对象Figure,FigureCanvas,Axes。

需要导入一下几个模块:

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure
import numpy as np

首先简单介绍一下FigureCanvs 这是一个wxWidgets对象,继承自wxPanel,故可以通过其嵌入到wxWidgets应用程序。下面学习一个简单的实例:

from numpy import arange, sin, pi

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure
import wx
class CanvasFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self,None,-1,
                         'CanvasFrame',size=(550,350))

        self.SetBackgroundColour(wx.NamedColor("WHITE"))

        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        t = arange(0.0,3.0,0.01)
        s = sin(2*pi*t)

        self.axes.plot(t,s)
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()


class App(wx.App):

    def OnInit(self):
        'Create the main window and insert the custom frame'
        frame = CanvasFrame()
        frame.Show(True)

        return True

app = App(0)
app.MainLoop()

同笔记1介绍的面向对象方法基本一致,最后将figure加到FigureCanvas上面即可完成图像的绘制。

再前面导入from matplotlib.backends.backend_wx import NavigationToolbar2Wx可以创建导航工具栏,需要添加BoxSizer()对象来控制排版。


你可能感兴趣的:(python,Class,insert,import,wxPython,matplotlib)