简体   繁体   中英

Adding an image to text widget of Tkinter in python 2.7

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()

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM