使用 PIL.ImageTk 创建 tkinter.PhotoImage 对象时出现 AttributeError

AttributeError when creating tkinter.PhotoImage object with PIL.ImageTk

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

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

ImageTk.PhotoImagePIL.ImageTk.PhotoImage 中的 class 与 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


编辑:

第一个link现在坏了,这是新的link:

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

我的解决方案是这样的:

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()