【问题标题】:How to embed image file (jpeg or png) onto a figure canvas in tkinter root window?如何将图像文件(jpeg 或 png)嵌入到 tkinter 根窗口中的图形画布上?
【发布时间】:2021-08-06 19:25:46
【问题描述】:

我正在使用 tkinter 编写一个 GUI,在脚本启动时,我希望根窗口显示一个由简单图像文件(最好是 jpeg 或 png)组成的画布。到目前为止,这是我的尝试:

from tkinter import Tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib import pyplot as plt
import matplotlib.image as mpimg

root = Tk()
root.wm_title("My Window")
root.geometry('1500x1000')
root.configure(bg='lightgrey')

background = mpimg.imread('background.png')
fig=plt.imshow(background)
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack(side=TOP)

这会产生错误消息,“AttributeError: 'AxesImage' 对象没有属性 'set_canvas'”,我不明白如何解释。我尝试使用 tkinter 的 PhotoImage 进行试验,但会产生类似的错误。

【问题讨论】:

  • 你能显示整个错误吗?因为在您的代码中既没有 AxesImage 也没有 set_canvas
  • this

标签: python matplotlib tkinter


【解决方案1】:

fig 不是 matplotlib Figure 对象。您需要创建Figure() 的实例并使用它来保存图像:

fig, ax = plt.subplots()

background = plt.imread('background.png')
ax.imshow(background)

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack(side=TOP)

【讨论】:

    猜你喜欢
    • 2014-07-17
    • 1970-01-01
    • 2011-01-11
    • 2019-09-06
    • 2016-01-28
    • 2018-03-05
    • 1970-01-01
    相关资源
    最近更新 更多