fishbacp
fishbacp

Reputation: 1263

How to embed image file (jpeg or png) onto a figure canvas in tkinter root window?

I'm writing a GUI using tkinter, and at startup of the script I want the root window to display a canvas comprised of a simple image file (preferably jpeg or png). Here's my attempt thus far:

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)

This yields the error message, "AttributeError: 'AxesImage' object has no attribute 'set_canvas'" which I don't understand how to interpret. I've tried experimenting with tkinter's PhotoImage, that produces a similar error.

Upvotes: 1

Views: 799

Answers (1)

acw1668
acw1668

Reputation: 46678

fig is not matplotlib Figure object. You need to create an instance of Figure() and use it to hold the image:

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)

Upvotes: 2

Related Questions