1

I am trying to place an image resized with PIL in a tkinter.PhotoImage object.

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)

However, when I later try to call

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

I get an

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

While this:

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

doesn't raise an error. What am I doing wrong?

user7043649
  • 48
  • 1
  • 1
  • 7
  • 2
    Did you look at their implementations? They are not the same `PhotoImage` classes. They don't have the same implementation. You have to determine which one you want to use, and achieve your goal based on how that class is implemented. – idjaw Oct 19 '16 at 17:37
  • Oh, thank you, this explains it. Is there a way to convert the `ImageTk.Photoimage` object to a `tkinter.Photoimage` object, or do i have to save the PIL image first and then load it into a tkinter.PhotoImage through it's filename? – user7043649 Oct 19 '16 at 17:44
  • I've never used either of those modules. I simply looked at the code of each and saw they were different. You would have to look in to the documentation to see what your options are. Look at the answer that was just posted. There is info provided. – idjaw Oct 19 '16 at 17:47

2 Answers2

8

ImageTk.PhotoImage as in PIL.ImageTk.PhotoImage is not the same class as tk.PhotoImage (tkinter.PhotoImage) they just have the same name

here is ImageTk.PhotoImage docs: http://pillow.readthedocs.io/en/3.1.x/reference/ImageTk.html#PIL.ImageTk.PhotoImage as you can see there is no put method in it.

but ImageTk.PhotoImage do have it: http://epydoc.sourceforge.net/stdlib/Tkinter.PhotoImage-class.html


edit:

first link is now broken, this is the new link:

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

DorElias
  • 2,243
  • 15
  • 18
1

My solution was something like this:

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()
ChaosPredictor
  • 3,777
  • 1
  • 36
  • 46