【问题标题】:AttributeError when creating tkinter.PhotoImage object with PIL.ImageTk使用 PIL.ImageTk 创建 tkinter.PhotoImage 对象时出现 AttributeError
【发布时间】:2016-10-19 17:21:43
【问题描述】:

我正在尝试将使用 PIL 调整大小的图像放置在 tkinter.PhotoImage 对象中。

import tkinter as tk # I use Python3
from PIL import Image, ImageTk

master = tk.Tk()
img =Image.open(file_name)
image_resized=img.resize((200,200))
photoimg=ImageTk.PhotoImage(image_resized)

但是,当我稍后尝试调用时

photoimg.put( "#000000", (0,0) )

我得到一个

AttributError: 'PhotoImage' object has no attribute 'put'

此时:

photoimg=tk.PhotoImage(file=file_name)
photoimg.put( "#000000", (0,0))

不会引发错误。 我做错了什么?

【问题讨论】:

  • 你看过他们的实现了吗?它们不是相同的 PhotoImage 类。他们没有相同的实现。您必须确定要使用哪一个,并根据该类的实现方式来实现目标。
  • 哦,谢谢,这就解释了。有没有办法将ImageTk.Photoimage 对象转换为tkinter.Photoimage 对象,还是我必须先保存 PIL 图像,然后通过文件名将其加载到 tkinter.PhotoImage 中?
  • 我从来没有使用过这些模块中的任何一个。我只是查看了每个代码,发现它们是不同的。您必须查看文档以查看您的选择。看看刚刚发布的答案。提供了信息。

标签: python tkinter python-imaging-library photoimage


【解决方案1】:

ImageTk.PhotoImagePIL.ImageTk.PhotoImage 中的 tk.PhotoImage (tkinter.PhotoImage) 不是同一个类,它们只是同名

这是 ImageTk.PhotoImage 文档: http://pillow.readthedocs.io/en/3.1.x/reference/ImageTk.html#PIL.ImageTk.PhotoImage 如您所见,其中没有 put 方法。

ImageTk.PhotoImage 确实有: http://epydoc.sourceforge.net/stdlib/Tkinter.PhotoImage-class.html


编辑:

第一个链接现已断开,这是新链接:

https://pillow.readthedocs.io/en/stable/reference/ImageTk.html?highlight=ImageTK#PIL.ImageTk.PhotoImage

【讨论】:

  • 第一个链接坏了:(
  • 添加了一个新链接 :)
【解决方案2】:

我的解决方案是这样的:

from tkinter import *
from PIL import Image, ImageTk

root = Tk()

file = 'image.png'

zoom = 1.9

# open image
image = Image.open(file)
image_size = tuple([int(zoom * x)  for x in image.size])
x,y = tuple([int(x/2)  for x in image_size])

# canvas for image
canvas = Canvas(root, width=image_size[0], height=image_size[1], relief=RAISED, cursor="crosshair")
canvas.grid(row=0, column=0)

ImageTk_image = ImageTk.PhotoImage(image.resize(image_size))
image_on_canvas = canvas.create_image(0, 0, anchor = NW, image = ImageTk_image)

canvas.create_line(x-3, y, x+4, y, fill="#ff0000")
canvas.create_line(x, y-3, x, y+4, fill="#ff0000")
canvas.create_line(x, y, x+1, y, fill="#0000ff")

root.mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多