微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – 在tkinter GUI中导入matplotlib图. show()出错

我正在尝试在我的tkinter GUI中嵌入matplotlib图.经过多次尝试在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,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.

上面的例子给了我这个错误

Traceback (most recent call last):
  File "<tmp 1>",line 34,in <module>
    canvas.show()
  File "C:\pyzo2015a\lib\site-packages\matplotlib\backends\backend_tkagg.py",line 350,in draw
    tkagg.blit(self._tkphoto,self.renderer._renderer,colormode=2)
  File "C:\pyzo2015a\lib\site-packages\matplotlib\backends\tkagg.py",line 24,in blit
    tk.call("PyAggImagePhoto",photoimage,id(aggimage),colormode,id(bBox_array))
_tkinter.TclError

一个例子:

#!/usr/bin/env python
# -*- noplot -*-

import matplotlib as mpl
import numpy as np
import sys
if sys.version_info[0] < 3:
    import Tkinter as tk
else:
    import tkinter as tk
import matplotlib.backends.tkagg as tkagg
from matplotlib.backends.backend_agg import figureCanvasAgg


def draw_figure(canvas,figure,loc=(0,0)):
    """ Draw a matplotlib figure onto a Tk canvas

    loc: location of top-left corner of figure on canvas in pixels.

    Inspired by matplotlib source: lib/matplotlib/backends/backend_tkagg.py
    """
    figure_canvas_agg = figureCanvasAgg(figure)
    figure_canvas_agg.draw()
    figure_x,figure_y,figure_w,figure_h = figure.bBox.bounds
    figure_w,figure_h = int(figure_w),int(figure_h)
    photo = tk.PhotoImage(master=canvas,width=figure_w,height=figure_h)

    # Position: convert from top-left anchor to center anchor
    canvas.create_image(loc[0] + figure_w/2,loc[1] + figure_h/2,image=photo)

    # Unfortunatly,there's no accessor for the pointer to the native renderer
    tkagg.blit(photo,figure_canvas_agg.get_renderer()._renderer,colormode=2)

    # Return a handle which contains a reference to the photo object
    # which must be kept live or else the picture disappears
    return photo

# Create a canvas
w,h = 300,200
window = tk.Tk()
window.title("A figure in a canvas")
canvas = tk.Canvas(window,width=w,height=h)
canvas.pack()

# Generate some example data
X = np.linspace(0,2.0*3.14,50)
Y = np.sin(X)

# Create the figure we desire to add to an existing canvas
fig = mpl.figure.figure(figsize=(2,1))
ax = fig.add_axes([0,1,1])
ax.plot(X,Y)

# Keep this handle alive,or else figure will disappear
fig_x,fig_y = 100,100
fig_photo = draw_figure(canvas,fig,loc=(fig_x,fig_y))
fig_w,fig_h = fig_photo.width(),fig_photo.height()

# Add more elements to the canvas,potentially on top of the figure
canvas.create_line(200,50,fig_x + fig_w / 2,fig_y + fig_h / 2)
canvas.create_text(200,text="Zero-crossing",anchor="s")

# Let Tk take over
tk.mainloop()

这个给了我这个错误

Traceback (most recent call last):
      File "<tmp 2>",line 56,in <module>
        fig_photo = draw_figure(canvas,fig_y))
      File "<tmp 2>",line 32,in draw_figure
        tkagg.blit(photo,colormode=2)
      File "C:\pyzo2015a\lib\site-packages\matplotlib\backends\tkagg.py",in blit
        tk.call("PyAggImagePhoto",id(bBox_array))
    _tkinter.TclError

我不明白为什么这些例子不起作用.有人可以帮帮我吗?

解决方法

我有类似的问题,所以这对我有用,
如果您正在使用Windows我建议卸载枕头和matplotlib并从 here重新安装

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐