tkinterpython-imaging-libraryopenfiledialogphotoimagegetopenfilename

Tkinter filedialog askopenfilename function


I'm trying to open the file dialog (select file) window when a user presses a button by calling the function open:

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

root = Tk()
root.title('Application')


def open_file():
    root.filename = tkFileDialog.askopenfilename(initialdir="/", title="Select An Image", filetypes=(("jpeg files", "*.jpg"), ("gif files", "*.gif*"), ("png files", "*.png")))
    image_label = Label(root, text=root.filename)
    image_label.pack()
    my_image = ImageTk.PhotoImage(Image.open(root.filename))
    my_image_label = Label(root, image=my_image)
    my_image_label.pack()

my_button = Button(root, text="Open File", command=open_file)
my_button.pack()
root.mainloop()

however, after I select the chosen file and 'submit' it, it won't appear on the my_image_label i created (only a blank space the size of the pic appears) But when I used the open function content outside of the function (without calling the function) it worked.

Do you have any idea what seems to be the problem? and how can I fix it?


Solution

  • I don't have 2.7 installed, so here's my best guess: root.filename should just be filename I think.

    What does print root.filename return?

    Edit: My first guess is wrong. I've modified it to work in 3.6 and barely changed anything:

    from tkinter import *
    from tkinter import filedialog
    from PIL import ImageTk, Image
    
    root = Tk()
    root.title('Application')
    
    
    def open_file():
        filename = filedialog.askopenfilename(initialdir="/", title="Select An Image", filetypes=(("jpeg files", "*.jpg"), ("gif files", "*.gif*"), ("png files", "*.png")))
        image_label = Label(root, text=filename)
        image_label.pack()
        my_image = ImageTk.PhotoImage(Image.open(filename))
        my_image_label = Label(root, image=my_image)
        my_image_label.pack()
    
    my_button = Button(root, text="Open File", command=open_file)
    my_button.pack()
    root.mainloop()
    

    Is it possible for you to work in a newer version of python? Or do you have to learn 2.7?

    Edit: Forget anything I said. Just add this line: my_image_label.photo = my_image before you pack the label.