精华内容
下载资源
问答
  • Matplotlib嵌入GUI界面

    千次阅读 2019-09-02 11:21:57
    1.将Matplotlib嵌入wxPython的GUI界面中 # -*- coding: utf-8 -*- import wx import numpy as np import matplotlib # matplotlib采用WXAgg为后台,将matplotlib嵌入wxPython中 matplotlib.use("WXAgg") from ...

    1.将Matplotlib嵌入wxPython的GUI界面中

    # -*- coding: utf-8 -*-
    
    import wx
    import numpy as np
    import matplotlib
    
    # matplotlib采用WXAgg为后台,将matplotlib嵌入wxPython中
    matplotlib.use("WXAgg")
    
    from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
    from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg as NavigationToolbar
    from matplotlib.ticker import MultipleLocator, FuncFormatter
    
    import pylab
    from matplotlib import pyplot
    
    
    ######################################################################################
    class MPL_Panel_base(wx.Panel):
        ''''' #MPL_Panel_base面板,可以继承或者创建实例'''
    
        def __init__(self, parent):
            wx.Panel.__init__(self, parent=parent, id=-1)
    
            self.Figure = matplotlib.figure.Figure(figsize=(4, 3))
            self.axes = self.Figure.add_axes([0.1, 0.1, 0.8, 0.8])
            self.FigureCanvas = FigureCanvas(self, -1, self.Figure)
    
            self.NavigationToolbar = NavigationToolbar(self.FigureCanvas)
    
            self.StaticText = wx.StaticText(self, -1, label='Show Help String')
    
            self.SubBoxSizer = wx.BoxSizer(wx.HORIZONTAL)
            self.SubBoxSizer.Add(self.NavigationToolbar, proportion=0, border=2, flag=wx.ALL | wx.EXPAND)
            self.SubBoxSizer.Add(self.StaticText, proportion=-1, border=2, flag=wx.ALL | wx.EXPAND)
    
            self.TopBoxSizer = wx.BoxSizer(wx.VERTICAL)
            self.TopBoxSizer.Add(self.SubBoxSizer, proportion=-1, border=2, flag=wx.ALL | wx.EXPAND)
            self.TopBoxSizer.Add(self.FigureCanvas, proportion=-10, border=2, flag=wx.ALL | wx.EXPAND)
    
            self.SetSizer(self.TopBoxSizer)
    
            ###方便调用
            self.pylab = pylab
            self.pl = pylab
            self.pyplot = pyplot
            self.numpy = np
            self.np = np
            self.plt = pyplot
    
        def UpdatePlot(self):
            '''''#修改图形的任何属性后都必须使用self.UpdatePlot()更新GUI界面 '''
            self.FigureCanvas.draw()
    
        def plot(self, *args, **kwargs):
            '''''#最常用的绘图命令plot '''
            self.axes.plot(*args, **kwargs)
            self.UpdatePlot()
    
        def semilogx(self, *args, **kwargs):
            ''''' #对数坐标绘图命令 '''
            self.axes.semilogx(*args, **kwargs)
            self.UpdatePlot()
    
        def semilogy(self, *args, **kwargs):
            ''''' #对数坐标绘图命令 '''
            self.axes.semilogy(*args, **kwargs)
            self.UpdatePlot()
    
        def loglog(self, *args, **kwargs):
            ''''' #对数坐标绘图命令 '''
            self.axes.loglog(*args, **kwargs)
            self.UpdatePlot()
    
        def grid(self, flag=True):
            ''''' ##显示网格  '''
            if flag:
                self.axes.grid()
            else:
                self.axes.grid(False)
    
        def title_MPL(self, TitleString="wxMatPlotLib Example In wxPython"):
            ''''' # 给图像添加一个标题   '''
            self.axes.set_title(TitleString)
    
        def xlabel(self, XabelString="X"):
            ''''' # Add xlabel to the plotting    '''
            self.axes.set_xlabel(XabelString)
    
        def ylabel(self, YabelString="Y"):
            ''''' # Add ylabel to the plotting '''
            self.axes.set_ylabel(YabelString)
    
        def xticker(self, major_ticker=1.0, minor_ticker=0.1):
            ''''' # 设置X轴的刻度大小 '''
            self.axes.xaxis.set_major_locator(MultipleLocator(major_ticker))
            self.axes.xaxis.set_minor_locator(MultipleLocator(minor_ticker))
    
        def yticker(self, major_ticker=1.0, minor_ticker=0.1):
            ''''' # 设置Y轴的刻度大小 '''
            self.axes.yaxis.set_major_locator(MultipleLocator(major_ticker))
            self.axes.yaxis.set_minor_locator(MultipleLocator(minor_ticker))
    
        def legend(self, *args, **kwargs):
            ''''' #图例legend for the plotting  '''
            self.axes.legend(*args, **kwargs)
    
        def xlim(self, x_min, x_max):
            ''' # 设置x轴的显示范围  '''
            self.axes.set_xlim(x_min, x_max)
    
        def ylim(self, y_min, y_max):
            ''' # 设置y轴的显示范围   '''
            self.axes.set_ylim(y_min, y_max)
    
        def savefig(self, *args, **kwargs):
            ''' #保存图形到文件 '''
            self.Figure.savefig(*args, **kwargs)
    
        def cla(self):
            ''' # 再次画图前,必须调用该命令清空原来的图形  '''
            self.axes.clear()
            self.Figure.set_canvas(self.FigureCanvas)
            self.UpdatePlot()
    
        def ShowHelpString(self, HelpString="Show Help String"):
            ''''' #可以用它来显示一些帮助信息,如鼠标位置等 '''
            self.StaticText.SetLabel(HelpString)
    
            ################################################################
    
    
    class MPL_Panel(MPL_Panel_base):
        ''''' #MPL_Panel重要面板,可以继承或者创建实例 '''
    
        def __init__(self, parent):
            MPL_Panel_base.__init__(self, parent=parent)
    
            # 测试一下
            self.FirstPlot()
    
    
            # 仅仅用于测试和初始化,意义不大
    
        def FirstPlot(self):
            # self.rc('lines',lw=5,c='r')
            self.cla()
            x = np.arange(-5, 5, 0.25)
            y = np.sin(x)
            self.yticker(0.5, 0.1)
            self.xticker(1.0, 0.2)
            self.xlabel('X')
            self.ylabel('Y')
            self.title_MPL("图像")
            self.grid()
            self.plot(x, y, '--^g')
    
    
            ###############################################################################
    
    
    # MPL_Frame添加了MPL_Panel的1个实例
    ###############################################################################
    class MPL_Frame(wx.Frame):
        """MPL_Frame可以继承,并可修改,或者直接使用"""
    
        def __init__(self, title="MPL_Frame Example In wxPython", size=(800, 500)):
            wx.Frame.__init__(self, parent=None, title=title, size=size)
    
            self.MPL = MPL_Panel_base(self)
    
            # 创建FlexGridSizer
            self.FlexGridSizer = wx.FlexGridSizer(rows=9, cols=1, vgap=5, hgap=5)
            self.FlexGridSizer.SetFlexibleDirection(wx.BOTH)
    
            self.RightPanel = wx.Panel(self, -1)
    
            # 测试按钮1
            self.Button1 = wx.Button(self.RightPanel, -1, "刷新", size=(100, 40), pos=(10, 10))
            self.Button1.Bind(wx.EVT_BUTTON, self.Button1Event)
    
            # 测试按钮2
            self.Button2 = wx.Button(self.RightPanel, -1, "关于", size=(100, 40), pos=(10, 10))
            self.Button2.Bind(wx.EVT_BUTTON, self.Button2Event)
    
            # 加入Sizer中
            self.FlexGridSizer.Add(self.Button1, proportion=0, border=5, flag=wx.ALL | wx.EXPAND)
            self.FlexGridSizer.Add(self.Button2, proportion=0, border=5, flag=wx.ALL | wx.EXPAND)
    
            self.RightPanel.SetSizer(self.FlexGridSizer)
    
            self.BoxSizer = wx.BoxSizer(wx.HORIZONTAL)
            self.BoxSizer.Add(self.MPL, proportion=-10, border=2, flag=wx.ALL | wx.EXPAND)
            self.BoxSizer.Add(self.RightPanel, proportion=0, border=2, flag=wx.ALL | wx.EXPAND)
    
            self.SetSizer(self.BoxSizer)
    
            # 状态栏
            self.StatusBar()
    
            # MPL_Frame界面居中显示
            self.Centre(wx.BOTH)
    
    
    
            # 按钮事件,用于测试
    
        def Button1Event(self, event):
            self.MPL.cla()  # 必须清理图形,才能显示下一幅图
            x = np.arange(-10, 10, 0.25)
            y = np.cos(x)
            self.MPL.plot(x, y, '--*g')
            self.MPL.xticker(2.0, 0.5)
            self.MPL.yticker(0.5, 0.1)
            self.MPL.title_MPL("MPL1")
            self.MPL.ShowHelpString("You Can Show MPL Helpful String Here !")
            self.MPL.grid()
            self.MPL.UpdatePlot()  # 必须刷新才能显示
    
        def Button2Event(self, event):
            self.AboutDialog()
    
    
            # 打开文件,用于测试
    
            def DoOpenFile(self):
                wildcard = r"Data files (*.dat)|*.dat|Text files (*.txt)|*.txt|ALL Files (*.*)|*.*"
                open_dlg = wx.FileDialog(self, message='Choose a file', wildcard=wildcard, style='')
                if open_dlg.ShowModal() == wx.ID_OK:
                    path = open_dlg.GetPath()
                    try:
                        file = open(path, 'r')
                        text = file.read()
                        file.close()
                    except:
                        dlg = wx.MessageDialog(self, 'Error opening file\n')
                        dlg.ShowModal()
    
                open_dlg.Destroy()
    
    
    
            # 自动创建状态栏
    
        def StatusBar(self):
            self.statusbar = self.CreateStatusBar()
            self.statusbar.SetFieldsCount(3)
            self.statusbar.SetStatusWidths([-2, -2, -1])
    
    
            # About对话框
    
        def AboutDialog(self):
            dlg = wx.MessageDialog(self,
                                   '\twxMatPlotLib\t\nMPL_Panel_base,MPL_Panel,MPL_Frame and MPL2_Frame \n Created by Wu Xuping\n Version 1.0.0 \n 2012-02-01',
                                   'About MPL_Frame and MPL_Panel', wx.OK | wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
    
            ###############################################################################
    
    
    ###  MPL2_Frame添加了MPL_Panel的两个实例
    ###############################################################################
    class MPL2_Frame(wx.Frame):
        """MPL2_Frame可以继承,并可修改,或者直接使用"""
    
        def __init__(self, title="MPL2_Frame Example In wxPython", size=(850, 500)):
            wx.Frame.__init__(self, parent=None, title=title, size=size)
    
            self.BoxSizer = wx.BoxSizer(wx.HORIZONTAL)
    
            self.MPL1 = MPL_Panel_base(self)
            self.BoxSizer.Add(self.MPL1, proportion=-1, border=2, flag=wx.ALL | wx.EXPAND)
    
            self.MPL2 = MPL_Panel_base(self)
            self.BoxSizer.Add(self.MPL2, proportion=-1, border=2, flag=wx.ALL | wx.EXPAND)
    
            self.RightPanel = wx.Panel(self, -1)
            self.BoxSizer.Add(self.RightPanel, proportion=0, border=2, flag=wx.ALL | wx.EXPAND)
    
            self.SetSizer(self.BoxSizer)
    
            # 创建FlexGridSizer
            self.FlexGridSizer = wx.FlexGridSizer(rows=9, cols=1, vgap=5, hgap=5)
            self.FlexGridSizer.SetFlexibleDirection(wx.BOTH)
    
            # 测试按钮1
            self.Button1 = wx.Button(self.RightPanel, -1, "TestButton", size=(100, 40), pos=(10, 10))
            self.Button1.Bind(wx.EVT_BUTTON, self.Button1Event)
    
            # 测试按钮2
            self.Button2 = wx.Button(self.RightPanel, -1, "AboutButton", size=(100, 40), pos=(10, 10))
            self.Button2.Bind(wx.EVT_BUTTON, self.Button2Event)
    
            # 加入Sizer中
            self.FlexGridSizer.Add(self.Button1, proportion=0, border=5, flag=wx.ALL | wx.EXPAND)
            self.FlexGridSizer.Add(self.Button2, proportion=0, border=5, flag=wx.ALL | wx.EXPAND)
    
            self.RightPanel.SetSizer(self.FlexGridSizer)
    
            # 状态栏
            self.StatusBar()
    
            # MPL2_Frame界面居中显示
            self.Centre(wx.BOTH)
    
    
    
            # 按钮事件,用于测试
    
        def Button1Event(self, event):
            self.MPL1.cla()  # 必须清理图形,才能显示下一幅图
            x = np.arange(-5, 5, 0.2)
            y = np.cos(x)
            self.MPL1.plot(x, y, '--*g')
            self.MPL1.xticker(2.0, 1.0)
            self.MPL1.yticker(0.5, 0.1)
            self.MPL1.title_MPL("MPL1")
            self.MPL1.ShowHelpString("You Can Show MPL1 Helpful String Here !")
            self.MPL1.grid()
            self.MPL1.UpdatePlot()  # 必须刷新才能显示
    
            self.MPL2.cla()
            self.MPL2.plot(x, np.sin(x), ':^b')
            self.MPL2.xticker(1.0, 0.5)
            self.MPL2.yticker(0.2, 0.1)
            self.MPL2.title_MPL("MPL2")
            self.MPL2.grid()
            self.MPL2.UpdatePlot()
    
        def Button2Event(self, event):
            self.AboutDialog()
    
    
    
            # 自动创建状态栏
    
        def StatusBar(self):
            self.statusbar = self.CreateStatusBar()
            self.statusbar.SetFieldsCount(3)
            self.statusbar.SetStatusWidths([-2, -2, -1])
    
    
            # About对话框
    
        def AboutDialog(self):
            dlg = wx.MessageDialog(self,
                                   '\twxMatPlotLib\t\nMPL_Panel_base,MPL_Panel,MPL_Frame and MPL2_Frame \n Created by Wu Xuping\n Version 1.0.0 \n 2012-02-01',
                                   'About MPL_Frame and MPL_Panel', wx.OK | wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
    
    
    
    
            ########################################################################
    
    
    # 主程序测试
    if __name__ == '__main__':
        app = wx.App()
        frame = MPL2_Frame()
        #frame = MPL_Frame()
        frame.Center()
        frame.Show()
        app.MainLoop()
    

    2.将Matplotlib嵌入Pyqt5的GUI界面

    import sys
    from PyQt5 import QtWidgets
    
    from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
    from matplotlib.backends.backend_qt5 import NavigationToolbar2QT as NavigationToolbar
    import matplotlib.pyplot as plt
    
    import random
    
    class Window(QtWidgets.QDialog):
        def __init__(self, parent=None):
            super(Window, self).__init__(parent)
    
            # a figure instance to plot on
            self.figure = plt.figure()
    
            # this is the Canvas Widget that displays the `figure`
            # it takes the `figure` instance as a parameter to __init__
            self.canvas = FigureCanvas(self.figure)
    
            # this is the Navigation widget
            # it takes the Canvas widget and a parent
            self.toolbar = NavigationToolbar(self.canvas, self)
    
            # Just some button connected to `plot` method
            self.button = QtWidgets.QPushButton('Plot')
            self.button.clicked.connect(self.plot)
    
            # set the layout
            layout = QtWidgets.QVBoxLayout()
            layout.addWidget(self.toolbar)
            layout.addWidget(self.canvas)
            layout.addWidget(self.button)
            self.setLayout(layout)
    
        def plot(self):
            ''' plot some random stuff '''
            # random data
            data = [random.random() for i in range(20)]
    
            # create an axis
            ax = self.figure.add_subplot(111)
    
            # discards the old graph
            ax.hold(False)
    
            # plot data
            ax.plot(data, '*-')
    
            # refresh canvas
            self.canvas.draw()
    
    if __name__ == '__main__':
        app = QtWidgets.QApplication(sys.argv)
    
        main = Window()
        main.show()
    
        sys.exit(app.exec_())

     

    展开全文
  • Matplotlib嵌入wxPython的GUI界面

    千次阅读 2017-11-19 20:49:22
    Matplotlib 是一个 Python 的 2D绘图库,它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形。有时候,我们想把matplotlib嵌入到wxpython,这样再利用pyinstaller打包便可形成一个脱离python编译器独立...

    Matplotlib 是一个 Python 的 2D绘图库,它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形。

    有时候,我们想把matplotlib嵌入到wxpython,这样再利用pyinstaller打包便可形成一个脱离python编译器独立的画图工具。

    下面是将matplotlib嵌入到wxpython的代码。

    参考资料:https://stackoverflow.com/questions/10737459/embedding-a-matplotlib-figure-inside-a-wxpython-panel

    # -*- coding: utf-8 -*-
    import wx
    import numpy as np
    import matplotlib
    
    # matplotlib采用WXAgg为后台,将matplotlib嵌入wxPython中
    matplotlib.use("WXAgg")
    
    from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
    from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg as NavigationToolbar
    from matplotlib.ticker import MultipleLocator, FuncFormatter
    
    import pylab
    from matplotlib import pyplot
    
    
    ######################################################################################
    class MPL_Panel_base(wx.Panel):
        ''''' #MPL_Panel_base面板,可以继承或者创建实例'''
    
        def __init__(self, parent):
            wx.Panel.__init__(self, parent=parent, id=-1)
    
            self.Figure = matplotlib.figure.Figure(figsize=(4, 3))
            self.axes = self.Figure.add_axes([0.1, 0.1, 0.8, 0.8])
            self.FigureCanvas = FigureCanvas(self, -1, self.Figure)
    
            self.NavigationToolbar = NavigationToolbar(self.FigureCanvas)
    
            self.StaticText = wx.StaticText(self, -1, label='Show Help String')
    
            self.SubBoxSizer = wx.BoxSizer(wx.HORIZONTAL)
            self.SubBoxSizer.Add(self.NavigationToolbar, proportion=0, border=2, flag=wx.ALL | wx.EXPAND)
            self.SubBoxSizer.Add(self.StaticText, proportion=-1, border=2, flag=wx.ALL | wx.EXPAND)
    
            self.TopBoxSizer = wx.BoxSizer(wx.VERTICAL)
            self.TopBoxSizer.Add(self.SubBoxSizer, proportion=-1, border=2, flag=wx.ALL | wx.EXPAND)
            self.TopBoxSizer.Add(self.FigureCanvas, proportion=-10, border=2, flag=wx.ALL | wx.EXPAND)
    
            self.SetSizer(self.TopBoxSizer)
    
            ###方便调用
            self.pylab = pylab
            self.pl = pylab
            self.pyplot = pyplot
            self.numpy = np
            self.np = np
            self.plt = pyplot
    
        def UpdatePlot(self):
            '''''#修改图形的任何属性后都必须使用self.UpdatePlot()更新GUI界面 '''
            self.FigureCanvas.draw()
    
        def plot(self, *args, **kwargs):
            '''''#最常用的绘图命令plot '''
            self.axes.plot(*args, **kwargs)
            self.UpdatePlot()
    
        def semilogx(self, *args, **kwargs):
            ''''' #对数坐标绘图命令 '''
            self.axes.semilogx(*args, **kwargs)
            self.UpdatePlot()
    
        def semilogy(self, *args, **kwargs):
            ''''' #对数坐标绘图命令 '''
            self.axes.semilogy(*args, **kwargs)
            self.UpdatePlot()
    
        def loglog(self, *args, **kwargs):
            ''''' #对数坐标绘图命令 '''
            self.axes.loglog(*args, **kwargs)
            self.UpdatePlot()
    
        def grid(self, flag=True):
            ''''' ##显示网格  '''
            if flag:
                self.axes.grid()
            else:
                self.axes.grid(False)
    
        def title_MPL(self, TitleString="wxMatPlotLib Example In wxPython"):
            ''''' # 给图像添加一个标题   '''
            self.axes.set_title(TitleString)
    
        def xlabel(self, XabelString="X"):
            ''''' # Add xlabel to the plotting    '''
            self.axes.set_xlabel(XabelString)
    
        def ylabel(self, YabelString="Y"):
            ''''' # Add ylabel to the plotting '''
            self.axes.set_ylabel(YabelString)
    
        def xticker(self, major_ticker=1.0, minor_ticker=0.1):
            ''''' # 设置X轴的刻度大小 '''
            self.axes.xaxis.set_major_locator(MultipleLocator(major_ticker))
            self.axes.xaxis.set_minor_locator(MultipleLocator(minor_ticker))
    
        def yticker(self, major_ticker=1.0, minor_ticker=0.1):
            ''''' # 设置Y轴的刻度大小 '''
            self.axes.yaxis.set_major_locator(MultipleLocator(major_ticker))
            self.axes.yaxis.set_minor_locator(MultipleLocator(minor_ticker))
    
        def legend(self, *args, **kwargs):
            ''''' #图例legend for the plotting  '''
            self.axes.legend(*args, **kwargs)
    
        def xlim(self, x_min, x_max):
            ''' # 设置x轴的显示范围  '''
            self.axes.set_xlim(x_min, x_max)
    
        def ylim(self, y_min, y_max):
            ''' # 设置y轴的显示范围   '''
            self.axes.set_ylim(y_min, y_max)
    
        def savefig(self, *args, **kwargs):
            ''' #保存图形到文件 '''
            self.Figure.savefig(*args, **kwargs)
    
        def cla(self):
            ''' # 再次画图前,必须调用该命令清空原来的图形  '''
            self.axes.clear()
            self.Figure.set_canvas(self.FigureCanvas)
            self.UpdatePlot()
    
        def ShowHelpString(self, HelpString="Show Help String"):
            ''''' #可以用它来显示一些帮助信息,如鼠标位置等 '''
            self.StaticText.SetLabel(HelpString)
    
            ################################################################
    
    
    class MPL_Panel(MPL_Panel_base):
        ''''' #MPL_Panel重要面板,可以继承或者创建实例 '''
    
        def __init__(self, parent):
            MPL_Panel_base.__init__(self, parent=parent)
    
            # 测试一下
            self.FirstPlot()
    
    
            # 仅仅用于测试和初始化,意义不大
    
        def FirstPlot(self):
            # self.rc('lines',lw=5,c='r')
            self.cla()
            x = np.arange(-5, 5, 0.25)
            y = np.sin(x)
            self.yticker(0.5, 0.1)
            self.xticker(1.0, 0.2)
            self.xlabel('X')
            self.ylabel('Y')
            self.title_MPL("图像")
            self.grid()
            self.plot(x, y, '--^g')
    
    
            ###############################################################################
    
    
    # MPL_Frame添加了MPL_Panel的1个实例
    ###############################################################################
    class MPL_Frame(wx.Frame):
        """MPL_Frame可以继承,并可修改,或者直接使用"""
    
        def __init__(self, title="MPL_Frame Example In wxPython", size=(800, 500)):
            wx.Frame.__init__(self, parent=None, title=title, size=size)
    
            self.MPL = MPL_Panel_base(self)
    
            # 创建FlexGridSizer
            self.FlexGridSizer = wx.FlexGridSizer(rows=9, cols=1, vgap=5, hgap=5)
            self.FlexGridSizer.SetFlexibleDirection(wx.BOTH)
    
            self.RightPanel = wx.Panel(self, -1)
    
            # 测试按钮1
            self.Button1 = wx.Button(self.RightPanel, -1, "刷新", size=(100, 40), pos=(10, 10))
            self.Button1.Bind(wx.EVT_BUTTON, self.Button1Event)
    
            # 测试按钮2
            self.Button2 = wx.Button(self.RightPanel, -1, "关于", size=(100, 40), pos=(10, 10))
            self.Button2.Bind(wx.EVT_BUTTON, self.Button2Event)
    
            # 加入Sizer中
            self.FlexGridSizer.Add(self.Button1, proportion=0, border=5, flag=wx.ALL | wx.EXPAND)
            self.FlexGridSizer.Add(self.Button2, proportion=0, border=5, flag=wx.ALL | wx.EXPAND)
    
            self.RightPanel.SetSizer(self.FlexGridSizer)
    
            self.BoxSizer = wx.BoxSizer(wx.HORIZONTAL)
            self.BoxSizer.Add(self.MPL, proportion=-10, border=2, flag=wx.ALL | wx.EXPAND)
            self.BoxSizer.Add(self.RightPanel, proportion=0, border=2, flag=wx.ALL | wx.EXPAND)
    
            self.SetSizer(self.BoxSizer)
    
            # 状态栏
            self.StatusBar()
    
            # MPL_Frame界面居中显示
            self.Centre(wx.BOTH)
    
    
    
            # 按钮事件,用于测试
    
        def Button1Event(self, event):
            self.MPL.cla()  # 必须清理图形,才能显示下一幅图
            x = np.arange(-10, 10, 0.25)
            y = np.cos(x)
            self.MPL.plot(x, y, '--*g')
            self.MPL.xticker(2.0, 0.5)
            self.MPL.yticker(0.5, 0.1)
            self.MPL.title_MPL("MPL1")
            self.MPL.ShowHelpString("You Can Show MPL Helpful String Here !")
            self.MPL.grid()
            self.MPL.UpdatePlot()  # 必须刷新才能显示
    
        def Button2Event(self, event):
            self.AboutDialog()
    
    
            # 打开文件,用于测试
    
            def DoOpenFile(self):
                wildcard = r"Data files (*.dat)|*.dat|Text files (*.txt)|*.txt|ALL Files (*.*)|*.*"
                open_dlg = wx.FileDialog(self, message='Choose a file', wildcard=wildcard, style='')
                if open_dlg.ShowModal() == wx.ID_OK:
                    path = open_dlg.GetPath()
                    try:
                        file = open(path, 'r')
                        text = file.read()
                        file.close()
                    except:
                        dlg = wx.MessageDialog(self, 'Error opening file\n')
                        dlg.ShowModal()
    
                open_dlg.Destroy()
    
    
    
            # 自动创建状态栏
    
        def StatusBar(self):
            self.statusbar = self.CreateStatusBar()
            self.statusbar.SetFieldsCount(3)
            self.statusbar.SetStatusWidths([-2, -2, -1])
    
    
            # About对话框
    
        def AboutDialog(self):
            dlg = wx.MessageDialog(self,
                                   '\twxMatPlotLib\t\nMPL_Panel_base,MPL_Panel,MPL_Frame and MPL2_Frame \n Created by Wu Xuping\n Version 1.0.0 \n 2012-02-01',
                                   'About MPL_Frame and MPL_Panel', wx.OK | wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
    
            ###############################################################################
    
    
    ###  MPL2_Frame添加了MPL_Panel的两个实例
    ###############################################################################
    class MPL2_Frame(wx.Frame):
        """MPL2_Frame可以继承,并可修改,或者直接使用"""
    
        def __init__(self, title="MPL2_Frame Example In wxPython", size=(850, 500)):
            wx.Frame.__init__(self, parent=None, title=title, size=size)
    
            self.BoxSizer = wx.BoxSizer(wx.HORIZONTAL)
    
            self.MPL1 = MPL_Panel_base(self)
            self.BoxSizer.Add(self.MPL1, proportion=-1, border=2, flag=wx.ALL | wx.EXPAND)
    
            self.MPL2 = MPL_Panel_base(self)
            self.BoxSizer.Add(self.MPL2, proportion=-1, border=2, flag=wx.ALL | wx.EXPAND)
    
            self.RightPanel = wx.Panel(self, -1)
            self.BoxSizer.Add(self.RightPanel, proportion=0, border=2, flag=wx.ALL | wx.EXPAND)
    
            self.SetSizer(self.BoxSizer)
    
            # 创建FlexGridSizer
            self.FlexGridSizer = wx.FlexGridSizer(rows=9, cols=1, vgap=5, hgap=5)
            self.FlexGridSizer.SetFlexibleDirection(wx.BOTH)
    
            # 测试按钮1
            self.Button1 = wx.Button(self.RightPanel, -1, "TestButton", size=(100, 40), pos=(10, 10))
            self.Button1.Bind(wx.EVT_BUTTON, self.Button1Event)
    
            # 测试按钮2
            self.Button2 = wx.Button(self.RightPanel, -1, "AboutButton", size=(100, 40), pos=(10, 10))
            self.Button2.Bind(wx.EVT_BUTTON, self.Button2Event)
    
            # 加入Sizer中
            self.FlexGridSizer.Add(self.Button1, proportion=0, border=5, flag=wx.ALL | wx.EXPAND)
            self.FlexGridSizer.Add(self.Button2, proportion=0, border=5, flag=wx.ALL | wx.EXPAND)
    
            self.RightPanel.SetSizer(self.FlexGridSizer)
    
            # 状态栏
            self.StatusBar()
    
            # MPL2_Frame界面居中显示
            self.Centre(wx.BOTH)
    
    
    
            # 按钮事件,用于测试
    
        def Button1Event(self, event):
            self.MPL1.cla()  # 必须清理图形,才能显示下一幅图
            x = np.arange(-5, 5, 0.2)
            y = np.cos(x)
            self.MPL1.plot(x, y, '--*g')
            self.MPL1.xticker(2.0, 1.0)
            self.MPL1.yticker(0.5, 0.1)
            self.MPL1.title_MPL("MPL1")
            self.MPL1.ShowHelpString("You Can Show MPL1 Helpful String Here !")
            self.MPL1.grid()
            self.MPL1.UpdatePlot()  # 必须刷新才能显示
    
            self.MPL2.cla()
            self.MPL2.plot(x, np.sin(x), ':^b')
            self.MPL2.xticker(1.0, 0.5)
            self.MPL2.yticker(0.2, 0.1)
            self.MPL2.title_MPL("MPL2")
            self.MPL2.grid()
            self.MPL2.UpdatePlot()
    
        def Button2Event(self, event):
            self.AboutDialog()
    
    
    
            # 自动创建状态栏
    
        def StatusBar(self):
            self.statusbar = self.CreateStatusBar()
            self.statusbar.SetFieldsCount(3)
            self.statusbar.SetStatusWidths([-2, -2, -1])
    
    
            # About对话框
    
        def AboutDialog(self):
            dlg = wx.MessageDialog(self,
                                   '\twxMatPlotLib\t\nMPL_Panel_base,MPL_Panel,MPL_Frame and MPL2_Frame \n Created by Wu Xuping\n Version 1.0.0 \n 2012-02-01',
                                   'About MPL_Frame and MPL_Panel', wx.OK | wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()
    
    
    
    
            ########################################################################
    
    
    # 主程序测试
    if __name__ == '__main__':
        app = wx.App()
        frame = MPL2_Frame()
        #frame = MPL_Frame()
        frame.Center()
        frame.Show()
        app.MainLoop()
    展开全文
  • 使用Python的tkinter和matplotlib模块在GUI界面中绘制PID交互曲线,用以观察各参数对PID控制的影响 最近学PID控制,想要直观的观察PID各部分参数对PID控制的影响,就用Python写了一个界面,如下: pid_GUI.py #!/...

    使用Python的tkinter和matplotlib模块在GUI界面中绘制PID交互曲线,用以观察各参数对PID控制的影响

    最近学PID控制,想要直观的观察PID各部分参数对PID控制的影响,就用Python写了一个界面,总的来说并不复杂,如下:

    pid_GUI.py

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # author:makang
    # Description: 绘制PID交互曲线,可以观察到Kp,Ki,Kd各参数对PID控制的影响
    
    import tkinter as tk
    import PID
    import matplotlib as plt
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    from matplotlib.figure import Figure
    import numpy as np
    
    # 绘图函数
    def drawPic():
        global r, g, b
    
        # 清空图像,以使得前后两次绘制的图像不会重叠
        # drawPic.f.clf()
        drawPic.a = drawPic.f.add_subplot(111)
        drawPic.a.grid(color='k', linestyle='-.')
        TestPID(Kp, Ki, Kd)
    
        # 每次绘图改变线条颜色用以区别----第一种方法
        # drawPic.a.plot(PositionalXaxis, PositionalYaxis, color=(r, g, b) )  # 绘制图形
        # r -= 0.15; g-=0.15; b-=0.15
        # if r < 0: r=0
        # if g < 0: g=0
        # if b < 0: b=0
    
        # 每次绘图改变线条颜色用以区别----第二种方法
        color = ['b', 'r', 'y', 'g', 'grey', 'coral', 'darkgreen', 'c', 'cyan', 'steelblue']
        drawPic.a.plot(PositionalXaxis, PositionalYaxis, color=color[np.random.randint(len(color))] )  # 绘制图形
        drawPic.canvas.draw()
        #每次绘图完毕清空x,y
        PositionalXaxis.clear()
        PositionalYaxis.clear()
    
    
    # 测试PID程序
    def TestPID(P, I, D):
        global PositionalXaxis, PositionalYaxis, fig_num
        PositionalPid = PID.PositionalPID(P, I, D)
        for i in range(1, 500):
            # 位置式
            PositionalPid.SetStepSignal(100.2)
            PositionalPid.SetInertiaTime(3, 0.1)
            PositionalYaxis.append(PositionalPid.SystemOutput)
            PositionalXaxis.append(i)
    
    #   改变Kp
    def Kp_enlarge():
        global Kp, Ki, Kd
        Kp += 0.2
        var_kp.set('%.2f'%Kp)
        drawPic()
        return Kp
    def Kp_reduce():
        global Kp
        Kp -= 0.2
        if Kp<=0:
            Kp=0
        var_kp.set('%.2f'%Kp)
        drawPic()
        return Kp
    
    #   改变Ki
    def Ki_enlarge():
        global Ki
        Ki += 0.2
        var_ki.set('%.2f'%Ki)
        drawPic()
        return Ki
    def Ki_reduce():
        global Ki
        Ki -= 0.2
        if Ki<=0:
            Ki=0
        var_ki.set('%.2f'%Ki)
        drawPic()
        return Ki
    
    #   改变Kd
    def Kd_enlarge():
        global Kd
        Kd += 0.2
        var_kd.set('%.2f'%Kd)
        drawPic()
        return Kd
    def Kd_reduce():
        global Kd
        Kd -= 0.2
        if Kd<=0:
            Kd=0
        var_kd.set('%.2f'%Kd)
        drawPic()
        return Kd
    
    
    #   清空图像
    def clear_pic():
        global r, g, b
        drawPic.f.clf()
        drawPic.canvas.draw()
        drawPic.a = drawPic.f.add_subplot(111)
        r = 0.6;
        g = 0.8;
        b = 0.8
    
    #   重置
    def reset():
        global Kp, Ki, Kd, r, g, b
        drawPic.f.clf()
        drawPic.canvas.draw()
        Kp=0.1
        Ki=0.1
        Kd=0.1
        var_kp.set('%.2f' % Kp)
        var_ki.set('%.2f' % Ki)
        var_kd.set('%.2f' % Kd)
        r = 0.6;
        g = 0.8;
        b = 0.8
    
    if __name__ == '__main__':
    
        # 实例化object,建立窗口window
        window = tk.Tk()
        # 给窗口的可视化起名字
        window.title('PID_GUI')
        # 设定窗口的大小(长 * 宽)
        window.geometry('800x700')  # 这里的乘是小x
        plt.use('TkAgg')
    
        var_kp = tk.StringVar()    # 将label标签的内容设置为字符类型,用var来接收函数的传出内容用以显示在标签上
        var_ki = tk.StringVar()
        var_kd = tk.StringVar()
        Kp=0.1
        Ki=0.1
        Kd=0.1
        var_kp.set('%.2f' % Kp)
        var_ki.set('%.2f' % Ki)
        var_kd.set('%.2f' % Kd)
        PositionalXaxis = [0]
        PositionalYaxis = [0]
    
        #定义颜色
        r=0.6; g=0.8; b=0.8
    
        # 绘图区域
        pic_area = tk.Label(window, bg='grey')
        pic_area.place(x=0, y=0, width='800', height='600')
        # 在Tk的GUI上放置一个画布
        drawPic.f = Figure(figsize=(5, 4), dpi=100)
        drawPic.canvas = FigureCanvasTkAgg(drawPic.f, master=pic_area)
        drawPic.canvas.draw()
        drawPic.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
    
    
        #调节控件
        Kp_label = tk.Label(textvariable=var_kp, bg='grey')
        Kp_label.place(x=20, y= 630, width='50', height='50')
        Kp_add_Btn = tk.Button(window, text='Kp Enlarge', font=('Arial', 10), width=10, height=1, command=Kp_enlarge)
        Kp_add_Btn.place(x=80, y=620, width='100', height='30')
        Kp_down_Btn = tk.Button(window,text='Kp Reduce', font=('Arial', 10), width=10, height=1, command=Kp_reduce)
        Kp_down_Btn.place(x=80, y=660, width='100', height='30')
    
        Ki_label = tk.Label(textvariable=var_ki, bg='grey')
        Ki_label.place(x=210, y= 630, width='50', height='50')
        Ki_add_Btn = tk.Button(window, text='Ki Enlarge', font=('Arial', 10), width=10, height=1, command=Ki_enlarge)
        Ki_add_Btn.place(x=270, y=620, width='100', height='30')
        Ki_down_Btn = tk.Button(window,text='Ki Reduce', font=('Arial', 10), width=10, height=1, command=Ki_reduce)
        Ki_down_Btn.place(x=270, y=660, width='100', height='30')
    
        Kd_label = tk.Label(textvariable=var_kd, bg='grey')
        Kd_label.place(x=400, y= 630, width='50', height='50')
        Kd_add_Btn = tk.Button(window, text='Kd Enlarge', font=('Arial', 10), width=10, height=1, command=Kd_enlarge)
        Kd_add_Btn.place(x=460, y=620, width='100', height='30')
        Kd_down_Btn = tk.Button(window,text='Kd Reduce', font=('Arial', 10), width=10, height=1, command=Kd_reduce)
        Kd_down_Btn.place(x=460, y=660, width='100', height='30')
    
        Clear_Btn = tk.Button(window, text='Clear', font=('Arial', 10), width=10, height=1, command=clear_pic)
        Clear_Btn.place(x=580, y=620, width='100', height='70')
    
        Reset_Btn = tk.Button(window, text='Reset', font=('Arial', 10), width=10, height=1, command=reset)
        Reset_Btn.place(x=680, y=620, width='100', height='70')
    
        window.mainloop()
        # 注意,loop因为是循环的意思,window.mainloop就会让window不断的刷新,如果没有mainloop,就是一个静态的window,传入进去的值就不会有循环,mainloop就相当于一个很大的while循环,有个while,每点击一次就会更新一次,所以我们必须要有循环
        # 所有的窗口文件都必须有类似的mainloop函数,mainloop是窗口文件的关键的关键。
    
    

    其中用到的PID是自定义模块,参考的别人的,用于对一阶惯性系统进行控制测试。
    PID.py

    #  PID控制一阶惯性系统测试程序
    
    import numpy as np
    
    # *****************************************************************#
    #                      增量式PID系统                              #
    # *****************************************************************#
    class IncrementalPID:
        def __init__(self, P, I, D):
            self.Kp = P
            self.Ki = I
            self.Kd = D
    
            self.PIDOutput = 0.0  # PID控制器输出
            self.SystemOutput = 0.0  # 系统输出值
            self.LastSystemOutput = 0.0  # 上次系统输出值
    
            self.Error = 0.0  # 输出值与输入值的偏差
            self.LastError = 0.0
            self.LastLastError = 0.0
    
        # 设置PID控制器参数
        def SetStepSignal(self, StepSignal):
            self.Error = StepSignal - self.SystemOutput
            IncrementValue = self.Kp * (self.Error - self.LastError) + self.Ki * self.Error + self.Kd * (
                        self.Error - 2 * self.LastError + self.LastLastError)
            self.PIDOutput += IncrementValue
            self.LastLastError = self.LastError
            self.LastError = self.Error
    
        # 设置一阶惯性环节系统  其中InertiaTime为惯性时间常数
        def SetInertiaTime(self, InertiaTime, SampleTime):
            self.SystemOutput = (InertiaTime * self.LastSystemOutput + SampleTime * self.PIDOutput) / (
                        SampleTime + InertiaTime)
            self.LastSystemOutput = self.SystemOutput
    
    
    # *****************************************************************#
    #                      位置式PID系统                              #
    # *****************************************************************#
    class PositionalPID:
        def __init__(self, P, I, D):
            self.Kp = P
            self.Ki = I
            self.Kd = D
    
            self.SystemOutput = 0.0
            self.ResultValueBack = 0.0
            self.PidOutput = 0.0
            self.PIDErrADD = 0.0
            self.ErrBack = 0.0
    
        def SetInertiaTime(self, InertiaTime, SampleTime):
            self.SystemOutput = (InertiaTime * self.ResultValueBack + SampleTime * self.PidOutput) / (
                        SampleTime + InertiaTime)
            self.ResultValueBack = self.SystemOutput
    
        def SetStepSignal(self, StepSignal):
            Err = StepSignal - self.SystemOutput
            KpWork = self.Kp * Err
            KiWork = self.Ki * self.PIDErrADD
            KdWork = self.Kd * (Err - self.ErrBack)
            self.PidOutput = KpWork + KiWork + KdWork
            self.PIDErrADD += Err
            self.ErrBack = Err
    

    有点难度的地方在于:一是要把Matplotlib图像放到界面上去;二是定义绘图函数,也用过别的方法,都不完美,现在这种方法可以实现需求。其中每次绘图使用不同的颜色可以有两种方法,一种是使用rgb数值,每次改变数值,另一种是定义颜色列表,每次随机选取。

    运行后的效果如下:

    在这里插入图片描述
    现在可以调节Kp,Ki,Kd的值来观察各参数对PID控制的影响。

    展开全文
  • 有时想在wxPython中使用Matplotlib,而不是使用命令行的格式调用,以下给出一个简单的实现的代码,更高级的可以google一下wxMPL或者wxmplot.# -*- coding: utf-8 -*-import wximport numpy as npimport matplotlib# ...

    有时想在wxPython中使用Matplotlib,而不是使用命令行的格式调用,以下给出一个简单的实现的代码,更高级的可以google一下wxMPL或者wxmplot.

    # -*- coding: utf-8 -*-

    import wx

    import numpy as np

    import matplotlib

    # matplotlib采用WXAgg为后台,将matplotlib嵌入wxPython中

    matplotlib.use("WXAgg")

    from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas

    from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg as NavigationToolbar

    from matplotlib.ticker import MultipleLocator, FuncFormatter

    import pylab

    from matplotlib import pyplot

    ######################################################################################

    class MPL_Panel_base(wx.Panel):

    ''' #MPL_Panel_base面板,可以继承或者创建实例'''

    def __init__(self,parent):

    wx.Panel.__init__(self,parent=parent, id=-1)

    self.Figure = matplotlib.figure.Figure(figsize=(4,3))

    self.axes = self.Figure.add_axes([0.1,0.1,0.8,0.8])

    self.FigureCanvas = FigureCanvas(self,-1,self.Figure)

    self.NavigationToolbar = NavigationToolbar(self.FigureCanvas)

    self.StaticText = wx.StaticText(self,-1,label='Show Help String')

    self.SubBoxSizer = wx.BoxSizer(wx.HORIZONTAL)

    self.SubBoxSizer.Add(self.NavigationToolbar,proportion =0, border = 2,flag = wx.ALL | wx.EXPAND)

    self.SubBoxSizer.Add(self.StaticText,proportion =-1, border = 2,flag = wx.ALL | wx.EXPAND)

    self.TopBoxSizer = wx.BoxSizer(wx.VERTICAL)

    self.TopBoxSizer.Add(self.SubBoxSizer,proportion =-1, border = 2,flag = wx.ALL | wx.EXPAND)

    self.TopBoxSizer.Add(self.FigureCanvas,proportion =-10, border = 2,flag = wx.ALL | wx.EXPAND)

    self.SetSizer(self.TopBoxSizer)

    ###方便调用

    self.pylab=pylab

    self.pl=pylab

    self.pyplot=pyplot

    self.numpy=np

    self.np=np

    self.plt=pyplot

    def UpdatePlot(self):

    '''#修改图形的任何属性后都必须使用self.UpdatePlot()更新GUI界面 '''

    self.FigureCanvas.draw()

    def plot(self,*args,**kwargs):

    '''#最常用的绘图命令plot '''

    self.axes.plot(*args,**kwargs)

    self.UpdatePlot()

    def semilogx(self,*args,**kwargs):

    ''' #对数坐标绘图命令 '''

    self.axes.semilogx(*args,**kwargs)

    self.UpdatePlot()

    def semilogy(self,*args,**kwargs):

    ''' #对数坐标绘图命令 '''

    self.axes.semilogy(*args,**kwargs)

    self.UpdatePlot()

    def loglog(self,*args,**kwargs):

    ''' #对数坐标绘图命令 '''

    self.axes.loglog(*args,**kwargs)

    self.UpdatePlot()

    def grid(self,flag=True):

    ''' ##显示网格 '''

    if flag:

    self.axes.grid()

    else:

    self.axes.grid(False)

    def title_MPL(self,TitleString="wxMatPlotLib Example In wxPython"):

    ''' # 给图像添加一个标题 '''

    self.axes.set_title(TitleString)

    def xlabel(self,XabelString="X"):

    ''' # Add xlabel to the plotting '''

    self.axes.set_xlabel(XabelString)

    def ylabel(self,YabelString="Y"):

    ''' # Add ylabel to the plotting '''

    self.axes.set_ylabel(YabelString)

    def xticker(self,major_ticker=1.0,minor_ticker=0.1):

    ''' # 设置X轴的刻度大小 '''

    self.axes.xaxis.set_major_locator( MultipleLocator(major_ticker) )

    self.axes.xaxis.set_minor_locator( MultipleLocator(minor_ticker) )

    def yticker(self,major_ticker=1.0,minor_ticker=0.1):

    ''' # 设置Y轴的刻度大小 '''

    self.axes.yaxis.set_major_locator( MultipleLocator(major_ticker) )

    self.axes.yaxis.set_minor_locator( MultipleLocator(minor_ticker) )

    def legend(self,*args,**kwargs):

    ''' #图例legend for the plotting '''

    self.axes.legend(*args,**kwargs)

    def xlim(self,x_min,x_max):

    ''' # 设置x轴的显示范围 '''

    self.axes.set_xlim(x_min,x_max)

    def ylim(self,y_min,y_max):

    ''' # 设置y轴的显示范围 '''

    self.axes.set_ylim(y_min,y_max)

    def savefig(self,*args,**kwargs):

    ''' #保存图形到文件 '''

    self.Figure.savefig(*args,**kwargs)

    def cla(self):

    ''' # 再次画图前,必须调用该命令清空原来的图形 '''

    self.axes.clear()

    self.Figure.set_canvas(self.FigureCanvas)

    self.UpdatePlot()

    def ShowHelpString(self,HelpString="Show Help String"):

    ''' #可以用它来显示一些帮助信息,如鼠标位置等 '''

    self.StaticText.SetLabel(HelpString)

    ################################################################

    class MPL_Panel(MPL_Panel_base):

    ''' #MPL_Panel重要面板,可以继承或者创建实例 '''

    def __init__(self,parent):

    MPL_Panel_base.__init__(self,parent=parent)

    #测试一下

    self.FirstPlot()

    #仅仅用于测试和初始化,意义不大

    def FirstPlot(self):

    #self.rc('lines',lw=5,c='r')

    self.cla()

    x = np.arange(-5,5,0.25)

    y = np.sin(x)

    self.yticker(0.5,0.1)

    self.xticker(1.0,0.2)

    self.xlabel('X')

    self.ylabel('Y')

    self.title_MPL("wxMatPlotLib Example In wxPython")

    self.grid()

    self.plot(x,y,'--^g')

    ###############################################################################

    # MPL_Frame添加了MPL_Panel的1个实例

    ###############################################################################

    class MPL_Frame(wx.Frame):

    """MPL_Frame可以继承,并可修改,或者直接使用"""

    def __init__(self,title="MPL_Frame Example In wxPython",size=(800,500)):

    wx.Frame.__init__(self,parent=None,title = title,size=size)

    self.MPL = MPL_Panel_base(self)

    #创建FlexGridSizer

    self.FlexGridSizer=wx.FlexGridSizer( rows=9, cols=1, vgap=5,hgap=5)

    self.FlexGridSizer.SetFlexibleDirection(wx.BOTH)

    self.RightPanel = wx.Panel(self,-1)

    #测试按钮1

    self.Button1 = wx.Button(self.RightPanel,-1,"TestButton",size=(100,40),pos=(10,10))

    self.Button1.Bind(wx.EVT_BUTTON,self.Button1Event)

    #测试按钮2

    self.Button2 = wx.Button(self.RightPanel,-1,"AboutButton",size=(100,40),pos=(10,10))

    self.Button2.Bind(wx.EVT_BUTTON,self.Button2Event)

    #加入Sizer中

    self.FlexGridSizer.Add(self.Button1,proportion =0, border = 5,flag = wx.ALL | wx.EXPAND)

    self.FlexGridSizer.Add(self.Button2,proportion =0, border = 5,flag = wx.ALL | wx.EXPAND)

    self.RightPanel.SetSizer(self.FlexGridSizer)

    self.BoxSizer=wx.BoxSizer(wx.HORIZONTAL)

    self.BoxSizer.Add(self.MPL,proportion =-10, border = 2,flag = wx.ALL | wx.EXPAND)

    self.BoxSizer.Add(self.RightPanel,proportion =0, border = 2,flag = wx.ALL | wx.EXPAND)

    self.SetSizer(self.BoxSizer)

    #状态栏

    self.StatusBar()

    #MPL_Frame界面居中显示

    self.Centre(wx.BOTH)

    #按钮事件,用于测试

    def Button1Event(self,event):

    self.MPL.cla()#必须清理图形,才能显示下一幅图

    x=np.arange(-10,10,0.25)

    y=np.cos(x)

    self.MPL.plot(x,y,'--*g')

    self.MPL.xticker(2.0,0.5)

    self.MPL.yticker(0.5,0.1)

    self.MPL.title_MPL("MPL1")

    self.MPL.ShowHelpString("You Can Show MPL Helpful String Here !")

    self.MPL.grid()

    self.MPL.UpdatePlot()#必须刷新才能显示

    def Button2Event(self,event):

    self.AboutDialog()

    #打开文件,用于测试

    def DoOpenFile(self):

    wildcard = r"Data files (*.dat)|*.dat|Text files (*.txt)|*.txt|ALL Files (*.*)|*.*"

    open_dlg = wx.FileDialog(self,message='Choose a file',wildcard = wildcard, >

    13657627564280.gif

    # -*- coding: utf-8 -*-

    import wx

    from wxMatPlotLib import MPL_Panel,MPL_Frame,MPL2_Frame,pylab,pyplot,np

    class wxMPL_Frame(MPL2_Frame):

    """MPL2_Frame可以继承,并可修改,或者直接使用"""

    def __init__(self,title="wxMPL_Frame Example In wxPython",size=(850,500)):

    MPL2_Frame.__init__(self,title=title,size=size)

    self.Button1.SetLabel('Plot')

    if __name__ == '__main__':

    app = wx.PySimpleApp()

    frame = wxMPL_Frame()

    frame.Show()

    app.MainLoop()

    13657627565691.gif

    展开全文
  • 有时想在wxPython中使用Matplotlib,而不是使用命令行的格式调用,以下给出一个简单的实现的代码,更高级的可以google一下wxMPL或者wxmplot. # -*- coding: utf-8 -*- import wx import numpy as np import ...
  • matplotlib non-GUI backend 无法显示图片解决办法问题分析新的问题 问题分析 根据提示,表明现在的显示方式,是非GUI图形界面显示的。所以在调用pylab.show()的时候会有这样的一个提示。那么,既然有非GUI的显示...
  • Pyqt5 + matplotlib 的在 GUI中 图片呈现

    千次阅读 2019-04-30 19:53:10
    Pyqt5 + matplotlib 的在 GUI中 图片呈现 个人原创,未经允许,不可转载!!! 1. 在QtDesigner中设计UI界面 层次如下:From----->Widget------>GroupBox 2. 转成.py文件 # -*- coding: utf-8 -*- ...
  • 在PyQt5设计的GUI界面中显示matplotlib绘制的图形

    万次阅读 多人点赞 2018-05-03 17:34:18
    一、matplotlib如何嵌入PyQt5中? 通过matplotlib.backends.backend_qt5agg类连接PyQt5。在实际代码中,我们需要在引用部分加入内容: import matplotlib matplotlib.use("Qt5Agg") # 声明使用QT5 from ...
  • import matplotlib matplotlib.use("Agg") 具体可以参考(levy_cui)的博客。
  • 此时,将 tkinter 与 matplotlib 结合,是最好的选择。 知识点: 将 tkinter 与 matplotlib 结合的整个套路是固定的,只需要关心我们的绘图逻辑和程序逻辑即可 import matplotlib matplotlib.use('TkA...
  • 之前我们在Python的GUI工具中嵌入了Matplotlib,制作一个基础版的股票行情分析界面:专题研究|量化交易怎么少得了GUI!手把手教你用 Python 打造股票行情分析界面那么换成嵌入pyecharts又会是怎么样的效果呢?p...
  • 我编写了以下脚本,该脚本创建了一个空GUI,其中包含一个调用Matplotlib图表的按钮:import sysimport osfrom PyQt4 import QtGuifrom PyQt4 import *import matplotlib.pyplot as pltclass SmallGUI(QtGui....
  • python gui界面实例_python爬取电影数据(含GUI界面版) pip install matplotlib pip install numpy pip install tushare pip install pandas pip install wxPython​
  • Linux服务器没有GUI的情况下使用matplotlib绘图 需求描述: Linux服务器没有GUI 或者 远程单纯使用 Xshell等 命令窗口来 操作 Linux 使用 plt.plot 等弹窗画图时,因为没有 GUI或者 使用的 操作方法 不支持 画图...
  • 在数据分析的过程中,往往需要对所建立的模型进行可视化,并调整其中的某些参数。 通常情况下,在Python中...这样,可以在展示出的GUI界面中动态的调整模型的参数,并绘制图像。 最终实现的效果如下: 可以通过GUI界...
  • 1、运行后报错: Matplotlib is currently using agg, which is a non-GUI backend 按照网上说的办法,添加了matplotlib.use(‘TkAgg’),报没有Tktink包 2、通过pip install 下载tktink包会报找不到包。 查了很多...

空空如也

空空如也

1 2 3 4 5 ... 8
收藏数 143
精华内容 57
关键字:

matplotlib界面gui