Tkinter和PIL无法加载jpeg图片

3
我正在尝试让我的Tkinter程序能够从标准的.gif文件中加载和显示.jpg文件。
import Image,ImageTk
root = Tk()
PILFile = Image.open("Image.jpg")
Image = PhotoImage(file=PILFile)
ImageLabel = Label(root,image=Image)
ImageLabel.image = Image
ImageLabel.pack()
root.mainloop()

我收到的错误信息如下:
Traceback (most recent call last):
  File "/home/paragon/Programs/Python/Web/MP3Tagger.py", line 25, in <module>
albumart = PhotoImage(file=PILfile)
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 3271, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 3227, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
 _tkinter.TclError: couldn't open "<JpegImagePlugin.JpegImageFile image mode=RGB size=1500x1500 at 0x98AEFCC>": no such file or directory
 [Finished in 0.4s with exit code 1]

我非常确定文件以正确的格式存在,我可能做错了什么?


@falsetru 我认为Tkinter标签不支持JPG图像。 - Rushy Panchal
@F3AR3DLEGEND,标签不是问题。代码正在使用ImageTk,对吧? - falsetru
2个回答

6

根据The Tkinter PhotoImage类:

The PhotoImage class can read GIF and PGM/PPM images from files:

.... If you need to work with other file formats, the Python Imaging Library (PIL) contains classes that lets you load images in over 30 formats, and convert them to Tkinter-compatible image objects:

from PIL import Image, ImageTk

image = Image.open("lenna.jpg")
photo = ImageTk.PhotoImage(image)

-> 用ImageTk.PhotoImage替换Tkinter.PhotoImage

root = Tk()
PILFile = Image.open("Image.jpg")
Image = ImageTk.PhotoImage(PILFile) # <---
ImageLabel = Label(root, image=Image)
ImageLabel.image = Image
ImageLabel.pack()
root.mainloop()

1
您的错误是由于参数file引起的:
Image = PhotoImage(file=PILFile)

这将指定文件路径。此外,您需要使用ImageTk.PhotoImage。而不是,您需要:
Image = ImageTk.PhotoImage(PILFile)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接