25

How do I insert a JPEG image into a Python 2.7 Tkinter window? What is wrong with the following code? The image is called Aaron.jpg.

#!/usr/bin/python

import Image
import Tkinter
window = Tkinter.Tk()

window.title("Join")
window.geometry("300x300")
window.configure(background='grey')

imageFile = "Aaron.jpg"

window.im1 = Image.open(imageFile)


raw_input()
window.mainloop()
Aaron Esau
  • 1,083
  • 3
  • 15
  • 31

3 Answers3

60

Try this:

import tkinter as tk
from PIL import ImageTk, Image

#This creates the main window of an application
window = tk.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')

path = "Aaron.jpg"

#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img = ImageTk.PhotoImage(Image.open(path))

#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
panel = tk.Label(window, image = img)

#The Pack geometry manager packs widgets in rows or columns.
panel.pack(side = "bottom", fill = "both", expand = "yes")

#Start the GUI
window.mainloop()

Related docs: ImageTk Module, Tkinter Label Widget, Tkinter Pack Geometry Manager

Seanny123
  • 8,776
  • 13
  • 68
  • 124
NorthCat
  • 9,643
  • 16
  • 47
  • 50
  • 9
    Note that the original PIL won't work with Python 3, but Pillow is pretty much a drop-in replacement: https://pillow.readthedocs.io/en/latest/index.html – Caspar Aug 29 '16 at 05:03
  • 2
    Re @Caspar's comment, at command line for Python 3(.6), do `pip install pillow` to get the module. – Engineer Jun 19 '18 at 18:32
  • 5
    As a note, additional "popup" windows that contain images need the image to be specified outside of Label instantiation as well (e.g. `label = tk.Label(window, image=img)` then `label.image = img` before finally `label.pack()`) – Chris Collett Mar 30 '21 at 17:54
1
import tkinter as tk
from tkinter import ttk
from PIL import Image,  ImageTk
win = tk. Tk()
image1 = Image. open("Aoran. jpg")
image2 =  ImageTk. PhotoImage(image1)
image_label = ttk. Label(win , image =.image2)
image_label.place(x = 0 , y = 0)
win.mainloop()
-3
from tkinter import *
from PIL import ImageTk, Image

window = Tk()
window.geometry("1000x300")

path = "1.jpg"

image = PhotoImage(Image.open(path))

panel = Label(window, image = image)

panel.pack()

window.mainloop()
Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46