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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With