我在使用tkinter运行Matplotlib时遇到了一致的问题。这种情况发生在我的代码和其他代码中,包括我从网上下载的示例代码,可能适用于其他代码。
当我使用IPython控制台而不是标准Python控制台时,会发生matplotlib.use('TkAgg')
的初始用户警告。我认为这只是意味着IPython更加冗长,因为在任何一种情况下,程序都会在canvas.show()
上崩溃。我一直试图运行的完整代码来自Matplotlib网站:
#!/usr/bin/env python
import matplotlib
matplotlib.use('TkAgg')
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
# Implement the default mpl key bindings
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import sys
if sys.version_info[0] < 3:
import Tkinter as Tk
else:
import tkinter as Tk
root = Tk.Tk()
root.wm_title("Embedding in TK")
f = Figure(figsize=(5, 4), dpi=100)
a = f.add_subplot(111)
t = arange(0.0, 3.0, 0.01)
s = sin(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)
def on_key_event(event):
print('you pressed %s' % event.key)
key_press_handler(event, canvas, toolbar)
canvas.mpl_connect('key_press_event', on_key_event)
def _quit():
root.quit() # Stops mainloop
root.destroy() # This is necessary on Windows to prevent
# Fatal Python Error: PyEval_RestoreThread: NULL tstate
button = Tk.Button(master=root, text='Quit', command=_quit)
button.pack(side=Tk.BOTTOM)
Tk.mainloop()
# If you put root.destroy() here, it will cause an error if
# the window is closed with the window manager.
使用调试器我将canvas.show跟随到tkinter(backend_tkagg.py):
def draw(self):
FigureCanvasAgg.draw(self)
tkagg.blit(self._tkphoto, self.renderer._renderer, colormode=2)
self._master.update_idletasks()
我跳过FigureCanvasAgg.draw确定并进入tkagg.blit ...注意传递给tkagg.blit的数据都不是应用程序数据。这个调用将我带到tkagg.py,即:
def blit(photoimage, aggimage, bbox=None, colormode=1):
tk = photoimage.tk
if bbox is not None:
bbox_array = bbox.__array__()
else:
bbox_array = None
data = np.asarray(aggimage)
try:
tk.call("PyAggImagePhoto", photoimage,
id(data), colormode, id(bbox_array))
except Tk.TclError:
try:
try:
_tkagg.tkinit(tk.interpaddr(), 1)
except AttributeError:
_tkagg.tkinit(id(tk), 0)
tk.call("PyAggImagePhoto", photoimage,
id(data), colormode, id(bbox_array))
except (ImportError, AttributeError, Tk.TclError):
raise
它在tk.call上反复失败,我认为这是对Tcl的调用。
我在这里修改了代码以将TclError作为变量捕获,因此我可以在调试器中检查它。它说:tclErr:无效的命令名称“PyAggImagePhoto”
我该怎么做?
答案 0 :(得分:0)
总结:
答案 1 :(得分:0)
替换后,此代码对我有用
NavigationToolbar2TkAgg
使用
NavigationToolbar2Tk
也被替换
canvas.show()
使用
canvas.draw()
注意,我使用Anaconda 4.8.3,Matplotlib 3.2.1,Tkinter 8.6和Windows 10。