【问题标题】:How can I open an image in Python?如何在 Python 中打开图像?
【发布时间】:2022-04-16 17:11:36
【问题描述】:
我看过很多教程,都试过了,但 Pygame、PIL、Tkinter 似乎没有任何效果。当然,这可能是因为我,因为我是个绿党……
from Tkinter import *
root = Tk()
photo = PhotoImage(file="too.jpg")
label = Label(root, image=photo)
label.pack()
root.mainloop()
【问题讨论】:
标签:
python
image
python-2.7
tkinter
【解决方案1】:
您的代码是正确的,但由于 jpgfile 的存在而无法正常工作。
如果您想使用 PhotoImage 类,您只能从文件中读取 GIF 和 PGM/PPM 图像(请参阅 docs)。
对于其他文件格式,您可以使用Python Imaging Library (PIL)。
这是您使用 PIL 的示例:
from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
image = Image.open("too.jpg")
photo = ImageTk.PhotoImage(image)
label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()
root.mainloop()
如果您想避免图像被垃圾收集,label.image = photo 行是必需的。