我有一个小的接口,可以将数据加载到matplotlib图中。我希望能够加载含有以前制作的情节的泡菜,但不知怎的,我无法使其发挥作用。
这是matplotlib在tkinter中嵌入绘图的示例之一:
import sys
import pickle
import matplotlib
from numpy import arange, sin, pi, cos
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
if sys.version_info[0] < 3:
import Tkinter as Tk
else:
import tkinter as Tk
def restore_from_pickle(pickle_address, fig):
fig.clear()
with open(pickle_address, 'rb') as fid:
fig = pickle.load(fid)
return
def _quit():
root.quit()
root.destroy()
def on_key_event(event):
print('you pressed %s' % event.key)
key_press_handler(event, canvas, toolbar)
matplotlib.use('TkAgg')
root = Tk.Tk()
root.wm_title("Embedding in TK")
f = Figure(figsize=(5, 4), dpi=100)
t = arange(0.0, 3.0, 0.01)
#Plot to store
a = f.add_subplot(111)
s = sin(2*pi*t)
a.plot(t, s)
#Saving to pickle
with open('figure_pickle', 'wb') as fid:
pickle.dump(f, fid)
#Initial plot display
f.clear()
a = f.add_subplot(111)
s = cos(2*pi*t)
a.plot(t, s)
# a tk.DrawingArea
canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
toolbar = NavigationToolbar2TkAgg(canvas, root)
toolbar.update()
canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
canvas.mpl_connect('key_press_event', on_key_event)
button = Tk.Button(master=root, text='f(sin)', command=restore_from_pickle('figure_pickle', f))
#button = Tk.Button(master=root, text='Quit', command=_quit)
button.pack(side=Tk.BOTTOM)
Tk.mainloop()
这会产生类似:
如果按下按钮,它会关闭窗口。我修改了它,因此它保存了一个包含一个数字的pickle,现在按钮加载了这个图像。但是,当我运行它时:
原始情节没有绘制,也没有画出那个......
发生了什么事?
感谢您的任何建议