2

Hello I am having issues with resizing my picture. I am trying to resize the image to fit the blue drawing. However the way I am doing it, returns an error.

File "gui.py", line 42, in fileDialog
self.display = Label(image=self.photo.resize((800, 600),Image.ANTIALIAS))
AttributeError: 'PhotoImage' object has no attribute 'resize

I am just testing it to see if it fits by doing 800,600 I really don't know.

def fileDialog(self):
    self.filename = filedialog.askopenfilename(title="Select")
    self.label = ttk.Label(self.labelFrame, text="")
    self.label.grid(column=1, row=2)
    self.label.configure(text=self.filename)
    self.photo= ImageTk.PhotoImage(file = self.filename)
    self.display = Label(image=self.photo.resize((800, 600),Image.ANTIALIAS))
    self.display.grid(row=0)

Insert image in blue drawing

Is there something that I am doing incorrectly? Please advise.

1 Answer 1

5

You need to resize the image, not the photoimage.

import tkinter as tk
from PIL import Image, ImageTk

filename = 'bell.jpg'
img = Image.open(filename)
resized_img = img.resize((200, 100))

root = tk.Tk()
root.photoimg = ImageTk.PhotoImage(resized_img)
labelimage = tk.Label(root, image=root.photoimg)
labelimage.pack()

enter image description here

To address the new question, you do not have to know the filename at the time of label creation. The following code produces the same result:

import tkinter as tk
from PIL import Image, ImageTk

root = tk.Tk()
labelimage = tk.Label(root)
labelimage.pack()

filename = 'bell.jpg'
img = Image.open(filename)
resized_img = img.resize((200, 100))
root.photoimg = ImageTk.PhotoImage(resized_img)
labelimage.configure(image=root.photoimg)
Sign up to request clarification or add additional context in comments.

7 Comments

Yes, but wouldn't self.photo contain the photo itself?
@beloas your self.photo contains a representation of the image, but that does not logically conclude that it can do any given task with it; no matter how you look at it, ImageTk.PhotoImage does not have a resize() method. ImageTk.PhotoImage can open a filename directly, but it is not designed for image manipulation. Image is.
I understand, I just am confused about how I would incorporate that in the filedialog function since self.photo doesn't really hold the image that is selected?
Please see updated question with screenshot of the blue drawing. I am wanting to fit the image into that area.
@beloas I'm not really sure what you want me to do here. I answered your question and you've chosen to ignore the answer... and point me back to the question. Your code is unchanged as I type this. ImageTk.PhotoImage does not have a resize() method. You need to store the image in an Image object if you want to perform manipulations upon it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.