使用FigureCanvasTkAgg在python中的同一图形上绘制多个图像

时间:2018-05-16 14:09:12

标签: python matplotlib tkinter

我想使用FigureCanvasTkAgg在python中的同一个图上绘制多个图像。当使用matplotlib我可以使用{import matplotlib.pyplot as plt} plt.imshow(image1) ; plt.pause(0.6) ; plt.imshow(image2) 由于我使用Tkinter,我使用FigureCanvasTkAgg来做同样的

   `f = Figure(figsize=(6,6))

    a = f.add_subplot(111)
    image = np.array(np.random.random((1024,1024))*100,dtype=int)
    a.imshow(image)

    canvas = FigureCanvasTkAgg(f, self)
    canvas.show()
    canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)`

有没有人可以帮我解决如何在FigureCanvasTkAgg中实现matplotlib的暂停效果。

1 个答案:

答案 0 :(得分:0)

您可以使用threading模块来安排函数的执行:

from threading import Thread

def wrapper():
    time.sleep(5)
    image = np.array(np.random.random((1024,1024))*100,dtype=int)
    ax.imshow(image)
    canvas.draw()

_t = Thread(target=wrapper)
_t.start()

这将在新线程中执行函数wrapper,因此原始程序可以同时继续。

这里有完整的例子:

#!/usr/bin/env python
import time
import tkinter as tk
from threading import Thread
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import numpy as np

root = tk.Tk()
f = Figure(figsize=(6,6))

ax = f.add_subplot(111)
# First image    
image = np.array(np.random.random((1024,1024))*100, dtype=int)
ax.imshow(image)

canvas = FigureCanvasTkAgg(f, root)
canvas.draw()
canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

def wrapper():
    time.sleep(5)
    # Second image appears after 5 seconds
    image = np.array(np.random.random((1024,1024))*100,dtype=int)
    ax.imshow(image)
    canvas.draw()

_t = Thread(target=wrapper)
_t.start()

root.mainloop()