将 PIL 图像转换为 Tkinter 图像时出错

Error while converting PIL image to Tkinter image

我正在尝试使用 Pillow 旋转 image

img = Image.open("./assets/aircraftCarrier/aircraftCarrier0.gif")

img = img.rotate(270)

这会旋转图像,但是当我尝试保存它时 Pillow 似乎无法识别文件类型,即使我在保存时输入格式类型也是如此:

img.save("./tempData/img", "GIF")

它想出了一个file with a blank extension

现在这并不重要,只要 tkinter 可以用 PhotoImage 识别它,但这似乎也不起作用:

img = PhotoImage(img)

label = Label(root, image=img)
label.pack()

我收到此错误消息:

TypeError: __str__ returned non-string (type Image)

我不太确定我做错了什么,或者我是否需要用 Pillow 做更多处理。

不胜感激,

乔希


完整代码:

import tkinter as tk
from tkinter import *
import tkinter
from PIL import Image

root = tk.Tk()
root.title("Test")


img = Image.open("./assets/aircraftCarrier/aircraftCarrier0.gif")

img = img.rotate(270)

img.save("./tempData/img", "GIF")

img = PhotoImage(img)

label = Label(root, image=img)
label.pack()

root.mainloop()

完整错误信息:

Traceback (most recent call last):
  File "C:\Users\Joshlucpoll\Documents\Battleships\test.py", line 19, in <module>
    label = Label(root, image=img)
  File "C:\Users\Joshlucpoll\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 2766, in __init__
    Widget.__init__(self, master, 'label', cnf, kw)
  File "C:\Users\Joshlucpoll\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 2299, in __init__
    (widgetName, self._w) + extra + self._options(cnf))
TypeError: __str__ returned non-string (type Image)

好的,查看 PhotoImageeffbot documentation 有这些代码行:

from PIL import Image, ImageTk

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

它指出:

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

因此,从 PIL 转换为 Tkinter 时,您似乎需要在 PhotoImage 之前添加 ImageTk

例如:

img = ImageTk.PhotoImage(img)

将此添加到我的程序中确实可以使旋转的图像完美显示。