【问题标题】:Error while converting PIL image to Tkinter image将 PIL 图像转换为 Tkinter 图像时出错
【发布时间】:2023-04-07 17:41:01
【问题描述】:

我正在尝试使用 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)

【问题讨论】:

  • 您正在尝试旋转 GIF,而不是 png 或 jpg。试过 png 或 jpg 看看是否只有 GIF 会出现错误?
  • @BlackThunder 对 jpg 和 png 都进行了尝试,但结果完全相同
  • 这看起来不正确:img = PhotoImage(img)。 Tkinter 的 PhotoImage 类不将图像作为其第一个参数。

标签: python python-3.x tkinter python-imaging-library photoimage


【解决方案1】:

好的,查看effbot documentationPhotoImage 有这些代码行:

from PIL import Image, ImageTk

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

它指出:

如果您需要使用其他文件格式,Python Imaging 库 (PIL) 包含可让您加载超过 30 个图像的类 格式,并将它们转换为与 Tkinter 兼容的图像对象

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

例如:

img = ImageTk.PhotoImage(img)

将它添加到我的程序中确实会导致旋转的图像完美显示。

【讨论】:

    猜你喜欢
    • 2015-12-31
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多