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

时间:2016-10-19 17:21:43

标签: python tkinter python-imaging-library photoimage

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

 Usage: hbase [<options>] <command> [<args>]
 Options:
  --config DIR    Configuration direction to use. Default: ./conf
  --hosts HOSTS   Override the list in 'regionservers' file

Commands:
Some commands take arguments. Pass no args or -h for usage.
shell           Run the HBase shell
hbck            Run the hbase 'fsck' tool
snapshot        Create a new snapshot of a table
snapshotinfo    Tool for dumping snapshot information
wal             Write-ahead-log analyzer
hfile           Store file analyzer
zkcli           Run the ZooKeeper shell
upgrade         Upgrade hbase
master          Run an HBase HMaster node
regionserver    Run an HBase HRegionServer node
zookeeper       Run a Zookeeper server
rest            Run an HBase REST server
thrift          Run the HBase Thrift server
thrift2         Run the HBase Thrift2 server
clean           Run the HBase clean up script
classpath       Dump hbase CLASSPATH
mapredcp        Dump CLASSPATH entries required by mapreduce
pe              Run PerformanceEvaluation
ltt             Run LoadTestTool
version         Print the version
CLASSNAME       Run the class named CLASSNAME

然而,当我后来尝试拨打

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'

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

2 个答案:

答案 0 :(得分:4)

<{1}}与ImageTk.PhotoImage中的PIL.ImageTk.PhotoImage不是tk.PhotoImagetkinter.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

答案 1 :(得分:0)

我的解决方案是这样的:

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