我试图在我的tkinter窗口中嵌入一个matplotlib图形,并使用以下代码作为基础,然后在我的主代码中使用它。 https://matplotlib.org/gallery/user_interfaces/embedding_in_tk_canvas_sgskip.html 如果我运行下面的代码,我得到以下错误: AttributeError:“_tkinter。对象没有属性TclError 代码:
import matplotlib as mpl
import numpy as np
import sys
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)
# Unfortunately, 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 * np.pi, 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, 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, 50, text="Zero-crossing", anchor="s")
# Let Tk take over
tk.mainloop()
有人能帮我解决这个错误吗?我在Stack Overflow上发现了类似的问题,但是针对不同的属性(‘choice’,‘getitems’,‘text’,‘PassCheck’等等)。谢谢。 问题来源StackOverflow 地址:/questions/59466692/attributeerror-tkinter-tkapp-object-has-no-attribute-tclerror
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
替换import matplotlib as mpl为:
from matplotlib.figure import Figure
然后替换import matplotlib.backends.tkagg as tkagg为
from matplotlib.backends import _backend_tk
最后,替换该行:
tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
与:
_backend_tk.blit(
photo, figure_canvas_agg.get_renderer()._renderer, (0, 1, 2, 3))