Tkinter photo not changing after file selection

Viewed 124

I'm trying to implement a simple python GUI program that allows the user to select a photo and view it in the window for reference.

Here's my code for it:

from tkinter import *
from tkinter.filedialog import askopenfilename
from PIL import Image, ImageTk

filename = "none"
photo1 = ImageTk.PhotoImage

def fileSelect():
    global filename
    filename = askopenfilename() #input file  
    
    global photo1
    imageShow = Image.open(filename)
    imageShow = imageShow.resize((300, 350), Image.ANTIALIAS) 
    photo1 = ImageTk.PhotoImage(imageShow)     

window = Tk() #Creating window
window.title("Example") #Title of window

imageFirst = Image.open("first.jpg")
imageFirst = imageFirst.resize((300, 350), Image.ANTIALIAS)
photo1 = ImageTk.PhotoImage(imageFirst)
Label (window, image=photo1, bg="white").pack(pady=30) #Display image

Button(window, text="Select File", font="none 16", width=15, command=fileSelect).pack(pady=15)

window.mainloop()

As you may see, photo1 is declared global to allow the fileSelect() function to access and change it. When the program starts, it is to display a default initial image which will be replaced by the user selected image later.

The issue I'm facing is that after the user selects the image, the original photo disappears but the new selected image does not appear. I don't understand why this is happening. Any help please?

1 Answers

Here you go, start by changing your labels like this, so that it does not return None.

img_l = Label(window, image=photo1, bg="white")
img_l.pack(pady=30) #Display image

and then, change your function to:

def fileSelect():
    global filename, photo1 #keeping reference
    filename = askopenfilename() #input file  
    imageShow = Image.open(filename).resize((300, 350), Image.ANTIALIAS)
    photo1 = ImageTk.PhotoImage(imageShow) #instantiate  
    img_l.config(image=photo1) #updating the image
  • The config() method updates the image of the label, changing the image of the PhotoImage instance wont help.

  • Also you can remove the photo1 = ImageTk.PhotoImage on top of your code, as its of no use.

  • Though keep in mind, not selecting any files, will still return an error. Here is a way around:

    def fileSelect():
        global filename, photo1
        try:
            filename = askopenfilename() #input file  
            imageShow = Image.open(filename).resize((300, 350), Image.ANTIALIAS) 
            photo1 = ImageTk.PhotoImage(imageShow)   
            img_l.config(image=photo1)
        except AttributeError:
            pass
    

Hope this solved the error, do let me know if any doubts.

Cheers

Related