【发布时间】:2014-09-18 01:42:58
【问题描述】:
我正在尝试从控制台运行一些代码,但得到了 TclError。以下是整个回溯:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
return self.func(*args)
File "SM_analyser.py", line 446, in OnB_maxq
self.canvas = FigureCanvasTkAgg(self.plotter, self)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 225, in __init__
master=master, width=w, height=h, borderwidth=4)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2195, in __init__
Widget.__init__(self, master, 'canvas', cnf, kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2055, in __init__
(widgetName, self._w) + extra + self._options(cnf))
TclError: can't invoke "canvas" command: application has been destroyed
我有理由确定以下代码块是负责任的。它应该将 plot 'figure' 添加到 tkinter 画布,但是当我运行它时,'figure' 被绘制在一个单独的窗口中并且给出了 Tcl 错误。
self.plotter = plt.figure('figure')
plt.contour(array, linewidths = 1, colors = 'k')
plt.contourf(array, cmap = plt.cm.jet)
plt.ylabel('Y', fontdict = {'fontsize':16})
plt.xlabel('A', fontdict = {'fontsize':16})
plt.colorbar()
plt.title('figure', fontdict = {'fontsize':20})
plt.show()
self.canvas = FigureCanvasTkAgg(self.plotter, self)
self.canvas.get_tk_widget().grid(column=14,row=2,rowspan=34)
plt.close()
self.canvas._tkcanvas.config(highlightthickness=0)
【问题讨论】:
-
您正在混合 pyplot 接口和嵌入。请参阅matplotlib.org/examples/user_interfaces/embedding_in_tk.html 我对 TK 的了解不够多,只能将您指向该示例并建议您不要导入
pyplot如果您正在进行嵌入(由于图形管理器创建新窗口并且由于可能存在的问题事件循环)。 -
@tcaswell 我之前尝试过解决这个问题,但无济于事。我找不到任何可以绘制没有 pyplot 的等高线图的地方。真正奇怪的是,我的代码从我的解释器(Spyder,而不是 IDLE)完美运行,但是当我从控制台运行它时出现此错误。
-
几乎所有的
pyplot命令或多或少都是plt.foo(..)plt.gca().foo(..)形式的瘦包装器。如果您引用了axes.Axes对象,只需调用contour即可。 -
@tcaswell 好的,所以我使用
ax = self.plotter.gca()生成了对轴的引用并在其上调用了轮廓。效果很好,谢谢。在这种情况下,将颜色条和轮廓图添加到图中的正确方法是什么? -
这些是图形方法,因此您只需要获取图形对象的引用(可能是您的
self.plotter),然后是fig.colorbar()。您可能还需要将 ref 传递给contourf返回的艺术家。
标签: python python-2.7 matplotlib tkinter