在python中添加图片时出错

2024-10-06 10:22:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,正在使用python3.5版本。我想将photo添加到python中,下面是我编写的代码:

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

但是当我运行它时,出现了以下错误:

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"
>>> 

Tags: sampleinpyimageinittkintermypublic
1条回答
网友
1楼 · 发布于 2024-10-06 10:22:24

Photoimage本机只能加载pngpgm&ppm图像(http://effbot.org/tkinterbook/photoimage.htm)。你知道吗

可以通过PIL加载其他图像格式。对于python3,使用Pillow如下:

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 answerHow do I insert a JPEG image into a python Tkinter window?中找到所有这些信息。你知道吗

相关问题 更多 >