Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am new in python and I am using python 3.5 version. I want to add photo to python, and here's the code I wrote:

from tkinter import *
win=Tk()
win.title("Python Image")

canvas=Canvas(win,width=500,height=500)
canvas.pack()

my_image=PhotoImage(file="C:\Users\Public\Pictures\Sample Pictures\Desert.jpg")
canvas.create_image(0,0,anchor=NW,image=my_image)


win.mainloop()

But when I run it, the following error occurred:

Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
================ RESTART: C:UsersLABE-2Desktop
akibul.py ================
Traceback (most recent call last):
  File "C:UsersLABE-2Desktop
akibul.py", line 8, in <module>
    my_image=PhotoImage(file="C:\Users\Public\Pictures\Sample Pictures\Desert.jpg")
  File "C:UsersLABE-2AppDataLocalProgramsPythonPython36-32lib	kinter\__init__.py", line 3539, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:UsersLABE-2AppDataLocalProgramsPythonPython36-32lib	kinter\__init__.py", line 3495, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "C:UsersPublicPicturesSample PicturesDesert.jpg"
>>> 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
746 views
Welcome To Ask or Share your Answers For Others

1 Answer

Photoimage can natively only load png and pgm&ppm images (http://effbot.org/tkinterbook/photoimage.htm).

You can load other image formats via PIL. For python3 use Pillow like this:

from PIL  import Image, ImageTk
from tkinter import Tk,Canvas,NW
win=Tk()
win.title("Python Image")

canvas=Canvas(win,width=500,height=500)
canvas.pack()

# use your path here ...
my_image = ImageTk.PhotoImage(Image.open(r"some.jpg"))
canvas.create_image(0,0,anchor=NW,image= my_image )

win.mainloop()

You could have found all this information in NorthCats answer to How do I insert a JPEG image into a python Tkinter window? as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...