从Tkinter gui中更新matplotlib imshow

时间:2013-10-26 22:05:47

标签: python matplotlib tkinter

我正在尝试在Tkinter gui中的matplotlib imshow窗口中更新数据,我的代码示例如下:

#minimal example...

import matplotlib, sys
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib import pylab as plt
from scipy import ndimage

if sys.version_info[0] < 3:
    import Tkinter as Tk
else:
    import tkinter as Tk

root = Tk.Tk()
root.wm_title("minimal example")

image = plt.imread('test.jpg')
fig = plt.figure(figsize=(5,4))
im = plt.imshow(image) # later use a.set_data(new_data)
ax = plt.gca()
ax.set_xticklabels([]) 
ax.set_yticklabels([]) 

# a tk.DrawingArea
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

def rotate(*args):
    print 'rotate button press...'
    theta = 90
    rotated = ndimage.rotate(image, theta)
    im.set_data(rotated)
    root.update()

def quit(*args):
    print 'quit button press...'
    root.quit()     
    root.destroy() 

button_rotate = Tk.Button(master = root, text = 'Rotate', command = rotate)
button_quit = Tk.Button(master = root, text = 'Quit', command = quit)

button_quit.pack(side=Tk.LEFT)
button_rotate.pack()

Tk.mainloop()

如您所见,我使用imshow()加载图像,然后尝试使用set_data()更新图像的数据,然后使用root.update()更新gui的根窗口。执行时,执行打印'旋转按钮按下''行,但其余部分似乎没有。我是否需要将图像手柄传递给旋转功能,或者返回旋转的图像?

1 个答案:

答案 0 :(得分:2)

需要重新绘制画布,试试这个:

def rotate(*args):
    print 'rotate button press...'
    theta = 90
    rotated = ndimage.rotate(image, theta)
    im.set_data(rotated)
    canvas.draw()

更新以继续旋转

请注意,这会将image保存为root的属性。也许不是最好的方法,但它适用于这个例子。

root = Tk.Tk()
root.wm_title("minimal example")

root.image = plt.imread('test.jpg')
fig = plt.figure(figsize=(5,4))
im = plt.imshow(root.image) # later use a.set_data(new_data)
ax = plt.gca()
ax.set_xticklabels([]) 
ax.set_yticklabels([])

# a tk.DrawingArea
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

def rotate(*args):
    print 'rotate button press...'
    root.image = ndimage.rotate(root.image, 90)
    im.set_data(root.image)
    canvas.draw()