Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with Images in Python's Tkinter

Tags:

python

tkinter

I have been trying to include images in my Tkinter widgets, but nothing seems to work. Here's my code:

from Tkinter import *
from PIL import Image

root = Tk()
image = Image.open('images/myimage.jpg')
root.image = image
b = Radiobutton(root, text='Image',image=image,value='I')
b.pack()
root.mainloop()

The error I get is: Trac

eback (most recent call last):
  File "C:/Users/.../loadimages.py", line 7, in <module>
    b = Radiobutton(root, text='Image',image=image,value='I')
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 2714, in __init__
    Widget.__init__(self, master, 'radiobutton', cnf, kw)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1974, in __init__
    (widgetName, self._w) + extra + self._options(cnf))
TclError: image "<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=402x439 at 0x2A6B080>" doesn't exist

Most internet sources suggest keeping a reference to the image to avoid the garbage collector, but I don't see how I could do that more than what I have here. There are also suggestions regarding having multiple Tk instances, but I only have one.

To whoever helps, thanks in advance!

like image 894
Derek Peirce Avatar asked Jan 13 '23 22:01

Derek Peirce


1 Answers

You need to convert the image you open using PIL into a PhotoImage:

from PIL import Image, ImageTk

image = Image.open("images/myimage.jpg")
photoimg = ImageTk.PhotoImage(image)
b = Radiobutton(root, image=photoimg)

See also: Photoimage API

like image 122
Yuushi Avatar answered Jan 17 '23 18:01

Yuushi