Home > Net >  How can I load an image into a tkinter window/canvas?
How can I load an image into a tkinter window/canvas?

Time:11-23

I am trying to have an image show up on a tkinter window. I have managed to do so in the past, but somehow my current attempt is failing at every step. Hopefully someone can guide me to the proper way and help me fix it.

I'm currently trying with this code. The error I'm getting is

_tkinter.TclError: image "paco_img" doesn't exist

from tkinter import *



PINK = "#e2979c"
RED = "#e7305b"
GREEN = "#9bdeac"
YELLOW = "#f7f5dd"
BLUE = "#678ac2"
FONT_NAME = "Courier"


window = Tk()
window.title("Thomas' Elevator Pitch")
window.config(padx=200, pady=100, bg=BLUE)

canvas = Canvas(width=5000, height=4000)

paco_img = PhotoImage(file="paco.png")
canvas.create_image(2500, 2000, image="paco_img")
canvas.pack()


I've also tried to do the following, which changes the error to

NameError: name 'ImageTk' is not defined. Did you mean: 'Image'?

However, when I do change ImageTk to Image, it shows PhotoImage as an unresolved attribute reference to Image.



window = Tk()
window.title("Thomas' Elevator Pitch")
window.config(padx=200, pady=100, bg=BLUE)

canvas = Canvas(width=5000, height=4000)

paco_img = ImageTk.PhotoImage(file="paco.png")
canvas.create_image(2500, 2000, image="paco_img")
canvas.pack()


I can't seem to wrap my head around it, and suggestions on similar questions asked here didn't work for me yet.

CodePudding user response:

As very well explained in comments by @JRiggles, first you need a Python library to handle the image.

Of course, you can install it with pip:

pip install Pillow

Then, using the tkinter hello-world-program as base, all you need to do is load the necessary libraries, load your image and to display it use either a button or a label widget image param:

from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk



root = Tk()
image = im = Image.open("/path/to/your/image.ext")
frm = ttk.Frame(root, padding=10)
frm.grid()
tk_image = ImageTk.PhotoImage(image)
ttk.Label(frm, image=tk_image).grid(column=0, row=0)
root.mainloop()
  • Related