r m*_*her 9 python tkinter matplotlib anaconda
我在使用 tkinter 运行Matplotlib时一直遇到问题。我的代码和其他人的代码都会发生这种情况,包括我从网上下载的示例代码,这些代码可能适用于其他人。
matplotlib.use('TkAgg')当我使用IPython控制台而不是标准 Python 控制台时,会出现初始用户警告。我认为这只是意味着 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.
Run Code Online (Sandbox Code Playgroud)
使用调试器,我按照 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()
Run Code Online (Sandbox Code Playgroud)
我跳过 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
Run Code Online (Sandbox Code Playgroud)
它在 tk.call 上反复失败,我认为这是对 Tcl 的调用。
我修改了此处的代码以将 TclError 捕获为变量,以便我可以在调试器中检查它。它说: tclErr:无效的命令名称“PyAggImagePhoto”
我对此有何看法?
总结一下: