Tkinter与pylab/matplotlib结合制作带播放、暂停、停止功能的颜色图动画:无法更新图形/画布?

4 投票
1 回答
7222 浏览
提问于 2025-04-16 01:36

我查了一下,但没有找到足够具体的问题,所以如果这问题重复了,我先说声抱歉。
目标是创建一个图形界面(GUI),可以不断更新图像,显示不同的矩阵数据,使用pylab的pcolor来绘制,这样就能形成一个动态的动画。不过用户应该能够通过Tkinter的按钮来播放、暂停和停止动画。

在我得到关于matplotlib如何使用set_array()、draw()和canvas.manager.after()的答案之前,我已经有了可以启动动画的代码,但我不知道怎么在仅使用matplotlib的功能时停止或暂停它,所以我决定直接使用Tkinter,而不是matplotlib的Tcl/Tk封装。这里有一段工作代码,看看有没有人有什么想法。不过接下来我会继续问我的真正问题。

# mouse click the "Play" button widget to play animation
# PROBLEMS:
# 1. can't pause or stop animation. once loop starts it cant be broken
# 2. set_array attribute for pcolor PolyCollection object only updates the matrix
# C of pcolor, however for my actual application, I will be using pcolor(x,y,C)
# and will have new x,y, and C per plot. Unlike line object, where set_xdata and
# set_ydata are used, I can't find an analogy to pcolor. If I were updating an
# image I could use set_data(x,y,C), but i am not importing an image. I assume
# pcolor is still my best bet unless (as in Matlab) there is an equivalent
# image(x,y,C) function?

import time as t
from pylab import *
from matplotlib.widgets import Button
ion()
def pressPlay(event):
    #fig=figure()
    ax = subplot(111)
    subplots_adjust(bottom=0.2)
    c=rand(5,5)
    cplot=pcolor(c)
    draw()
    for i in range(5):
        c=rand(5,5)
        cplot.set_array(c.ravel())
        cplot.autoscale()
        title('Ionosphere '+str(i+1))
        t.sleep(3)
        draw()
axPlay = axes([0.7, 0.05, 0.1, 0.075])
bPlay = Button(axPlay, 'Play')
bPlay.on_clicked(pressPlay)

顺便说一下,导入pylab时,TkAgg后端会自动设置为在matplotlib中使用……我想是这样。或者说我不知怎么就自动使用了TkAgg。我是在Linux上运行,Python版本是2.6.4,Ipython是0.10。

我修改了从Daniweb IT讨论社区找到的代码,使用Tkinter和update_idletasks()函数,这样我就可以播放、暂停和停止标签小部件的颜色变化。只要安装了Tkinter,这段代码可以单独在Python上运行。不需要使用matplotlib或pylab。这是工作代码,也是我后面问题的基础。

# This is meant to draw Start and Stop buttons and a label
# The Start button should start a loop in which the label
# is configured to change color by looping through a color list.
# At each pass through the loop the variable self.stop is checked:
# if True the loop terminates.
# The Stop button terminates the loop by setting the
# variable self.stop to True.
# The Start button restarts the animation from the beginning
# if Stop was hit last, or restarts the animation from where it left off
# if pause was hit last.
# The loop also terminates on the last color of the list, as if stop were hit


from Tkinter import *
colors = ['red','green','blue','orange','brown','black','white','purple','violet']
numcol=len(colors)
class SGWidget(Frame):
    def __init__(self, parent=None):
        Frame.__init__(self, parent)
        self.top_frame = Frame(bg='green')
        self.top_frame.grid()
        # enter event loop until all idle callbacks have been called.
        self.top_frame.update_idletasks()
        self.makeToolbar()
        # construct a label widget with the parent frame top_frame
        self.label = Label(self.top_frame,text = 'Text',bg='orange')
        self.label.grid()
 # initialize (time index t)
        self.t=0

    def makeToolbar(self):
        self.toolbar_text = ['Play','Pause','Stop']
        self.toolbar_length = len(self.toolbar_text)
        self.toolbar_buttons = [None] * self.toolbar_length

        for toolbar_index in range(self.toolbar_length):
            text = self.toolbar_text[toolbar_index]
            bg = 'yellow'
            button_id = Button(self.top_frame,text=text,background=bg)
            button_id.grid(row=0, column=toolbar_index)
            self.toolbar_buttons[toolbar_index] = button_id

            def toolbar_button_handler(event, self=self, button=toolbar_index):
                return self.service_toolbar(button)

            # bind mouse click on start or stop to the toolbar_button_handler
            button_id.bind("<Button-1>", toolbar_button_handler)

    # call blink() if start and set stop when stop            
    def service_toolbar(self, toolbar_index):
        if toolbar_index == 0:
            self.stop = False
            print self.stop
            self.blink()
        elif toolbar_index == 1:
            self.stop = True
            print self.stop
        elif toolbar_index == 2:
            self.stop = True
            print self.stop
            self.t=0

    # while in start, check if stop is clicked, if not, call blink recursivly
    def blink(self):
        if not self.stop:
            print 'looping',self.stop
            self.label.configure(bg=colors[self.t])
            self.t += 1
            if self.t == numcol: # push stop button
                self.service_toolbar(2)
            self.label.update_idletasks()
            self.after(500, self.blink)

if __name__ == '__main__':
    SGWidget().mainloop()

然后,在参考了matplotlib的示例embedding_in_tk.html后,http://matplotlib.sourceforge.net/examples/user_interfaces/embedding_in_tk.html,我修改了之前的代码,使得可以动画化一个与pcolor图形连接的画布。不过,我认为使用canvas.get_tk_widget()更新画布没有效果,可能是因为之前的命令重新绘制了pcolor()。所以我在想,每次重新绘制时是不是需要重新连接画布和图形?但我不知道怎么做。我希望我使用update_idletasks()的方向是对的???

所以,使用以下代码时,当代码在播放时,我看到的只是同一个图,而不是更新后的图?这是我主要的问题和疑问。

from pylab import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from Tkinter import *

colors=[None]*10
for i in range(len(colors)):
    colors[i]=rand(5,5)
    #colors = ['red','green','blue','orange','brown','black','white','purple','violet']
numcol=len(colors)

class App(Frame):
    def __init__(self,parent=None):
        Frame.__init__(self,parent)
        self.top=Frame()
        self.top.grid()
        self.top.update_idletasks()

        self.makeWidgets()
        self.makeToolbar()

    def makeWidgets(self):
        # figsize (w,h tuple in inches) dpi (dots per inch)
        #f = Figure(figsize=(5,4), dpi=100)
        self.f = Figure()
        self.a = self.f.add_subplot(111)
        self.a.pcolor(rand(5,5))
        # a tk.DrawingArea
        self.canvas = FigureCanvasTkAgg(self.f, master=self.top)
        self.canvas.get_tk_widget().grid(row=3,column=0,columnspan=3)
        self.bClose = Button(self.top, text='Close',command=self.top.destroy)
        self.bClose.grid()
        #self.label = Label(self.top, text = 'Text',bg='orange')
        #self.label.grid()
        # initialize (time index t)
        self.t=0

    def makeToolbar(self):
        self.toolbar_text = ['Play','Pause','Stop']
        self.toolbar_length = len(self.toolbar_text)
        self.toolbar_buttons = [None] * self.toolbar_length

        for toolbar_index in range(self.toolbar_length):
            text = self.toolbar_text[toolbar_index]
            bg = 'yellow'
            button_id = Button(self.top,text=text,background=bg)
            button_id.grid(row=0, column=toolbar_index)
            self.toolbar_buttons[toolbar_index] = button_id

            def toolbar_button_handler(event, self=self, button=toolbar_index):
                return self.service_toolbar(button)

            button_id.bind("<Button-1>", toolbar_button_handler)

    # call blink() if start and set stop when stop            
    def service_toolbar(self, toolbar_index):
        if toolbar_index == 0:
            self.stop = False
            print self.stop
            self.blink()
        elif toolbar_index == 1:
            self.stop = True
            print self.stop
        elif toolbar_index == 2:
            self.stop = True
            print self.stop
            self.t=0

    # while in start, check if stop is clicked, if not, call blink recursivly
    def blink(self):
        if not self.stop:
            print 'looping',self.stop
            self.a.pcolor(colors[self.t])
            #draw()
            #self.label.configure(bg=colors[self.t])
            self.t += 1
            if self.t == numcol: # push stop button
                self.service_toolbar(2)
            self.canvas.get_tk_widget().update_idletasks()
            #self.label.update_idletasks()
            self.after(500, self.blink)

#root = Tk()
app=App()
app.mainloop()

谢谢你的帮助!

1 个回答

2

在你的 blink 函数里,添加一个 self.canvas.show(),然后再去执行其他的空闲任务:

self.canvas.show() # insert this line
self.canvas.get_tk_widget().update_idletasks()

撰写回答