0

I have a Python (2.7.16) program with a function that aims to:

  • select a jpg file (via openfilename dialogue)
  • save that file to a new file name
  • close the file I have just created

Outside the function, I then try to open the saved file, but I get a "file not found" error. What am I doing wrong?

from tkinter import *
from PIL import Image as PIM
from tkinter.filedialog import askopenfilename

#Create a window
win= Tk()
win.geometry("1000x900+50+50")
win.title(" Display Images")

# Function to select and save an jpg image
def get_img():
    imgin=askopenfilename(initialdir='/home/pi/Python',title='Choose Image File',filetypes=[('Image files', '.jpg')])
    if imgin:
        img1 = PIM.open(imgin)
        img1.save("/home/pi/Python/thumb1.jpg")
        img1.close()

# Create a Label widget to hold the image
label= Label(win)
label.grid(row = 0, column = 0, columnspan = 2)

get_img()

label.configure(image = "/home/pi/Python/thumb1.jpg")
label.update()

win.mainloop()
  • Did you try to see if the file was actually saved to `/home/pi/Python`? – mgmussi Apr 09 '22 at 11:22
  • Yes. The thumb1.jpg file was created and remained in the folder after the program cancelled. I can open it with the standard image viewer. – Alan White Apr 09 '22 at 15:25
  • If it helps, the window I defined opens OK, but (obviously) no image is ever displayed. Thanks for taking the time to reply. – Alan White Apr 09 '22 at 15:26
  • I found [this answer](https://stackoverflow.com/a/3482156/13542462) that might help you. The problem is you didn't include `label.image = img` (in which case you'll have to import that image to a variable using `img = ImageTk.PhotoImage(Image.open(path))`), and that's allowing your image to be deleted before it gets displayed. – mgmussi Apr 09 '22 at 17:00
  • Many thanks mgmussi - the code now works. I can't claim to fully understand WHY, but now you have provided the answer, I can do some reading around to improve my knowledge. Thanks again. – Alan White Apr 09 '22 at 18:55

0 Answers0