1

I am new to Tkinter and i am trying to add an image to a text widget in Tkinter python 2.7 I have looked up some resources on the internet and as far as i have gotten is this code but it is giving error - "

File "anim.py", line 11, in <module>
    text.image_create(END,image=photoImg)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 2976, in image_create
    *self._options(cnf, kw))
  TypeError: __str__ returned non-string (type file) 

"

please tell me where i went wrong. Thanks in advance :)

from PIL import Image,ImageTk
from Tkinter import *
root = Tk()
root.geometry("900x900+100+100")
image1 = open('IMG_20160123_170503.jpg')
photoImg = PhotoImage(image1)
frame = Frame(root)
frame.pack()
text = Text(frame)
text.pack()
text.image_create(END,image=photoImg)
root.mainloop()
3
  • Text widget obviously does not support images. I recently needed pictures in a text widget. I used a canvas, put a frame on it and packed smaller frames on it as "lines" and inside these I added labels with text, and images. You can find everything how to do. Search for scrollable widgets on a canvas, images on labels and implement it to your code. Commented Feb 21, 2016 at 11:24
  • 3
    @Vivekkumarpathak I think people have hastily downvoted here. The Tkinter Text widget does support embedded images. Commented Feb 21, 2016 at 11:55
  • 1
    @JozefMéry: you are incorrect. The text widget does support embedded images. This is a well documented feature that has been in tkinter since the very beginning ot Tkinter. Commented Feb 21, 2016 at 14:23

1 Answer 1

7

You have made just two small mistakes. When you open the image as image1 you are using Python's built-in open keyword rather than Image.open, the method of PIL's Image class. You also reference Tkinter's PhotoImage class when you mean to reference PIL's ImageTk.PhotoImage class. Here is your fixed code:

from Tkinter import *
from PIL import Image,ImageTk
root = Tk()
root.geometry("900x900+100+100")
image1 = Image.open("IMG_20160123_170503.jpg")
photoImg = ImageTk.PhotoImage(image1)
frame = Frame(root)
frame.pack()
text = Text(frame)
text.pack()
text.image_create(END,image=photoImg)
root.mainloop()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You so much it really helped :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.