你自己PyQt4的GUI内Matplotlib动画 [英] Matplotlib animation inside your own PyQt4 GUI

查看:1703
本文介绍了你自己PyQt4的GUI内Matplotlib动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Python编写软件。我需要嵌入一个Matplotlib时间的动画成自制的GUI。这里有一些更多的细节关于他们:

I'm writing software in Python. I need to embed a Matplotlib time-animation into a self-made GUI. Here are some more details about them:

GUI是用Python写的,以及使用PyQt4的图书馆。我的GUI不是从公共的GUI可以找到的净非常不同。我只是继承 QtGui.QMainWindow 并添加一些按钮,布局,...

The GUI is written in Python as well, using the PyQt4 library. My GUI is not very different from the common GUIs you can find on the net. I just subclass QtGui.QMainWindow and add some buttons, a layout, ...

该Matplotlib动画是根据 animation.TimedAnimation 类。这里是code为动画:

The Matplotlib animation is based on the animation.TimedAnimation class. Here is the code for the animation:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import matplotlib.animation as animation

        class CustomGraph(animation.TimedAnimation):

        def __init__(self):

            self.n = np.linspace(0, 1000, 1001)
            self.y = 1.5 + np.sin(self.n/20)
            #self.y = np.zeros(self.n.size)


            # The window
            self.fig = plt.figure()
            ax1 = self.fig.add_subplot(1, 2, 1)
            self.mngr = plt.get_current_fig_manager() 
            self.mngr.window.setGeometry(50,100,2000, 800)

            # ax1 settings
            ax1.set_xlabel('time')
            ax1.set_ylabel('raw data')
            self.line1 = Line2D([], [], color='blue')
            ax1.add_line(self.line1)
            ax1.set_xlim(0, 1000)
            ax1.set_ylim(0, 4)


            animation.TimedAnimation.__init__(self, self.fig, interval=20, blit=True)


        def _draw_frame(self, framedata):
            i = framedata
            print(i)


            self.line1.set_data(self.n[ 0 : i ], self.y[ 0 : i ])

            self._drawn_artists = [self.line1]

        def new_frame_seq(self):
            return iter(range(self.n.size))

        def _init_draw(self):
            lines = [self.line1]
            for l in lines:
                l.set_data([], [])

        def showMyAnimation(self):
            plt.show()


    ''' End Class '''


    if __name__== '__main__':
        print("Define myGraph")
        myGraph = CustomGraph()
        myGraph.showMyAnimation()

这code产生一个​​简单的动画:

This code produces a simple animation:

正弦波动画

动画本身工作正常。运行code,动画在一个小窗口弹出,并开始运行。但我怎么嵌入动画在我自己自制的GUI?

The animation itself works fine. Run the code, the animation pops up in a small window and it starts running. But how do I embed the animation in my own self-made GUI?

我做了一些研究,以找出。这里有一些事情我试过了。我已经添加了以下code到Python文件。请注意,这增加code实际上是一个额外的类定义:

I have done some research to find out. Here are some things I tried. I have added the following code to the python file. Note that this added code is actually an extra class definition:

from PyQt4 import QtGui
from PyQt4 import QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas

class CustomFigCanvas(FigureCanvas):

    def __init__(self):

        self.myGraph = CustomGraph()
        FigureCanvas.__init__(self, self.myGraph.fig)

我试图在这里做的是嵌入在 CustomGraph()对象 - 这基本上是我的动画 - 成 FigureCanvas

What I try to do here is embedding the CustomGraph() object - which is essentially my animation - into a FigureCanvas.

我写我的GUI中的另一个Python文件(但仍处于同一个文件夹)。通常情况下,我可以添加窗口小部件到我的GUI。我认为,从类 CustomFigCanvas(..)的对象是通过继承一个Widget。所以这是我尝试在我的GUI:

I wrote my GUI in another python file (but still in the same folder). Normally I can add Widgets to my GUI. I believe that an object from the class CustomFigCanvas(..) is a Widget through inheritance. So this is what I try in my GUI:

    ..
    myFigCanvas = CustomFigCanvas()
    self.myLayout.addWidget(myFigCanvas)
    ..

它工作在一定程度上。我得到的确是我的GUI显示的数字。但这个数字是空的。动画不运行:

It works to some extent. I get indeed a figure displayed in my GUI. But the figure is empty. The animation doesn't run:

我的GUI功能失调动画

和甚至还有另一个奇怪的现象怎么回事。我的GUI显示这个空的身影,但我同时得到与它我的动画人物经常Matplotlib弹出窗口。另外这个动画没有运行。

And there is even another strange phenomenon going on. My GUI displays this empty figure, but I get simultaneously a regular Matplotlib popup window with my animation figure in it. Also this animation is not running.

有显然是我缺少的东西在这里。请帮我找出这个问题。我AP preciate非常所有帮助。

There is clearly something that I'm missing here. Please help me to figure out this problem. I appreciate very much all help.

推荐答案

我想我找到了解决办法。一切归功于哈里森先生谁做了Python教程网站 https://pythonprogramming.net 。他帮我。

I think I found the solution. All credit goes to Mr. Harrison who made the Python tutorial website https://pythonprogramming.net. He helped me out.

因此​​,这里是我做过什么。两大变化:

So here is what I did. Two major changes:

我previously有两大类: CustomGraph(TimedAnimation) CustomFigCanvas(FigureCanvas)。现在我只有一个离开,但他来自TimedAnimation和FigureCanvas继承: CustomFigCanvas(TimedAnimation,FigureCanvas)

I previously had two classes: CustomGraph(TimedAnimation) and CustomFigCanvas(FigureCanvas). Now I got only one left, but he inherits from both TimedAnimation and FigureCanvas: CustomFigCanvas(TimedAnimation, FigureCanvas)

这是我如何使pviously图$ P $:

This is how I made the figure previously:

self.fig = plt.figure()

通过专利法条约从import语句导入matplotlib.pyplot为PLT 到来。当你想将它嵌入到你自己的GUI使得数字显然这种方式引起麻烦。
因此,有一个更好的方式来做到这一点:

With 'plt' coming from the import statement 'import matplotlib.pyplot as plt'. This way of making the figure apparently causes troubles when you want to embed it into your own GUI. So there is a better way to do it:

self.fig = Figure(figsize=(5,5), dpi=100)

和现在的作品!

下面是完整的code:

Here is the complete code:

import numpy as np
from matplotlib.figure import Figure
from matplotlib.animation import TimedAnimation
from matplotlib.lines import Line2D

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas


    class CustomFigCanvas(FigureCanvas, TimedAnimation):

        def __init__(self):

            # The data
            self.n = np.linspace(0, 1000, 1001)
            self.y = 1.5 + np.sin(self.n/20)

            # The window
            self.fig = Figure(figsize=(5,5), dpi=100)
            ax1 = self.fig.add_subplot(111)

            # ax1 settings
            ax1.set_xlabel('time')
            ax1.set_ylabel('raw data')
            self.line1 = Line2D([], [], color='blue')
            ax1.add_line(self.line1)
            ax1.set_xlim(0, 1000)
            ax1.set_ylim(0, 4)

            FigureCanvas.__init__(self, self.fig)
            TimedAnimation.__init__(self, self.fig, interval = 20, blit = True)


        def _draw_frame(self, framedata):
            i = framedata
            print(i)


            self.line1.set_data(self.n[ 0 : i ], self.y[ 0 : i ])
            self._drawn_artists = [self.line1]

        def new_frame_seq(self):
            return iter(range(self.n.size))

        def _init_draw(self):
            lines = [self.line1]
            for l in lines:
                l.set_data([], [])


    ''' End Class '''

这就是code,使在matplotlib动画。现在您可以轻松将其嵌入到自己的Qt GUI:

That's the code to make the animation in matplotlib. Now you can easily embed it into your own Qt GUI:

    ..
    myFigCanvas = CustomFigCanvas()
    self.myLayout.addWidget(myFigCanvas)
    ..

看来工作pretty罚款。
谢谢哈里森!先生

It seems to work pretty fine. Thank you Mr. Harrison!

这篇关于你自己PyQt4的GUI内Matplotlib动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆