gpt4 book ai didi

python - 从 Tkinter gui 更新 matplotlib imshow

转载 作者:太空宇宙 更新时间:2023-11-03 11:31:12 25 4
gpt4 key购买 nike

我正在尝试更新 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com