在python中添加图片时发生错误 [英] an error occured to add picture in python

查看:1178
本文介绍了在python中添加图片时发生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,并且正在使用python 3.5版本.我想将照片添加到python,这是我写的代码:

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:\Users\LABE-2\Desktop\rakibul.py ================
Traceback (most recent call last):
  File "C:\Users\LABE-2\Desktop\rakibul.py", line 8, in <module>
    my_image=PhotoImage(file="C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg")
  File "C:\Users\LABE-2\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 3539, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Users\LABE-2\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 3495, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "C:\Users\Public\Pictures\Sample Pictures\Desert.jpg"
>>> 

推荐答案

Photoimage只能本地加载pngpgm&ppm图像( http://effbot.org/tkinterbook/photoimage.htm ).

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

您可以通过 PIL 加载其他图像格式.对于python3,使用枕头像这样:

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

您可能已经在 NorthCats答案中找到了所有这些信息. /questions/23901168/how-do-i-insert-a-jpeg-image-into-a-python-tkinter-window>如何将JPEG图像插入python Tkinter窗口?.

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.

这篇关于在python中添加图片时发生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆