python - 从 Tkinter gui 更新 matplotlib imshow

标签 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 的根窗口。执行时,会执行 print 'rotate button press...' 行,但其余部分似乎没有。我是否需要以某种方式将图像句柄传递给旋转函数,或者返回旋转后的图像?

最佳答案

Canvas 需要重绘,试试这个:

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()

关于python - 从 Tkinter gui 更新 matplotlib imshow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19612419/

相关文章:

python - 在 python matplotlib.dates 中绘制毫秒图

python - 如何在 matplotlib 中格式化极坐标等高线图

python - Raspberry Pi和Python(TKinter和Omxplayer)

python - 如何使用 Python 启动应用程序实例?

python - 使用 pandas 将 Excel 数据过滤到另一个 Excel

python - 在 Python 中遍历一个 unicode 字符串

python - 如何使用 matplotlib 在两个环之间填充

PYTHON - Tkinter 和 Selenium 文件转换自动化 : send_keys function returns no attribute & challenge with finding elements

python - 在 tkinter 中显示 Pandas 数据框

python - 从 Python 调用 FSCTL_CREATE_OR_GET_OBJECT_ID