0

I am trying to make a simple UI in python 2.7 with Tkinter module to browse and select image and display it on the UI but when i browse and select the image then the current image(initially loaded image) on the screen gets clear but the selected image is not displayed on the screen.

from Tkinter import * 
from PIL import ImageTk, Image
import tkFileDialog

root = Tk()
root.title('Simple Image Display app')

w = Canvas(root, width=1100, height=600)
w.pack()
root.resizable(width=FALSE, height=FALSE)

img = ImageTk.PhotoImage(Image.open('test_2.JPG').convert('LA'))
panel = Label(root, image = img)
panel.place(x=700,y=100)


def Open():       ## function to open file dialog and select the file to use in the reader application
    dialog = Tk()
    dialog.withdraw()
    fname = tkFileDialog.askopenfilename(filetypes = (("Image Files", "*.JPG"), ("All files", "*")))
    dialog.destroy()
    img = ImageTk.PhotoImage(Image.open(fname).convert('LA'))
    panel.configure(image = img)



menubar = Menu(root)

# File Menu
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Open", command=Open)
menubar.add_cascade(label="File", menu=filemenu)


# display the menu
root.config(menu=menubar)
root.mainloop()

any help or suggestion in fixing the issue ?

Thanks in advance.

sumit
  • 3,210
  • 1
  • 19
  • 37

2 Answers2

0

It looks like someone has had this issue on SO before: How to update the image of a Tkinter Label widget?

It boils down to Tkinter doing garbage collection on the image so it's out of scope. You want to add panel.image = img below your panel.configure(...) line.

Community
  • 1
  • 1
Nicholas Smith
  • 11,642
  • 6
  • 37
  • 55
0

after the suggested change from @nicholas-smith my code is working fine. here is the updated and working code for python 2.7

def Open():       ## function to open file dialog and select the file to use in the reader application
    dialog = Tk()
    dialog.withdraw()
    fname = tkFileDialog.askopenfilename(filetypes = (("Image Files", "*.JPG"), ("All files", "*")))
    dialog.destroy()
    img2 = ImageTk.PhotoImage(Image.open(fname).convert('LA'))
    panel.configure(image = img2)
    panel.image = img2

only "open" function needs to be modified.

sumit
  • 3,210
  • 1
  • 19
  • 37