I am having an issue with resizing an image using filedialog.

from PIL import Image, ImageTk

def fileDialog(self):
    self.filename = filedialog.askopenfilename(title="Select file")
    self.label = tk.Label(self.labelFrame, text = "")
    self.label.grid(column = 1, row = 2)
    self.label.configure(text=os.path.basename(self.filename))

    self.img = Image.open(self.filename)
    self.resized_img = self.img.resize((200, 100))

    self.photo = ImageTk.PhotoImage(file=self.resized_img)
    self.display = tk.Label(image=self.photo)
    self.display.grid(row=0)

The reason why I am doing this inside of the filedialog function is because I do not know the name of the file that will be chosen until the user clicks on the file. I do Image.open(self.filename) because filename holds the name of the file that the user clicks on once the file browser opens up. However, I get these errors. I do not want to do open('car.jpg') because it may be a different picture this is why I do open('self.filename').

Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python37- 
32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "gui.py", line 41, in fileDialog
self.photo = ImageTk.PhotoImage(file=self.resized_img)
File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site- 
packages\PIL\ImageTk.py", line 94, in __init__
image = _get_image_from_kw(kw)
File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site- 
packages\PIL\ImageTk.py", line 64, in _get_image_from_kw
return Image.open(source)
File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site- 
packages\PIL\Image.py", line 2661, in open
prefix = fp.read(16)
   AttributeError: 'Image' object has no attribute 'read'
   Exception ignored in: <function PhotoImage.__del__ at 0x03A63B70>
    Traceback (most recent call last):
   File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site- 
  packages\PIL\ImageTk.py", line 123, in __del__
   name = self.__photo.name
  AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'

Is there a reason I am getting this error? Please advise.

1 Answers

0
furas On Best Solutions

You have to remove file= in PhotoImage

self.photo = ImageTk.PhotoImage(self.resized_img)

file= needs filename, not object Image()

effbot.org: PhotoImage