繁体   English   中英

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

[英]AttributeError when creating tkinter.PhotoImage object with PIL.ImageTk

我试图在 tkinter.PhotoImage 对象中放置一个用 PIL 调整大小的图像。

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.PhotoImage中的PIL.ImageTk.PhotoImagetk.PhotoImage ( tkinter.PhotoImage ) 不是同一个类,它们只是具有相同的名称

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

ImageTk.PhotoImage确实有它: http : ImageTk.PhotoImage


编辑:

第一个链接现已损坏,这是新链接:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM