Python Tkinter - Find image file path from PhotoImage

Music Champ29 picture Music Champ29 · Sep 1, 2014 · Viewed 8.7k times · Source

I have a PhotoImage in tkinter called al_p4 but I want to be able to print the file path of the image. Can anyone help. Here is my code:

al_p4 = Image.open("Media/DVD/image.jpg").resize((100, 150), Image.ANTIALIAS)
al_p4 = ImageTk.PhotoImage(al_p4)

Thanks in advance guys ;)

Answer

Gustav picture Gustav · Sep 3, 2014

Because I'm still having trouble interpreting exactly what you mean, here are four different answers regarding how to go about printing.

If you simply need to print it and the path will always be constant, use:

print("Media/DVD/image.jpg")

If you need to print something and the path will be different, try:

filepath = "Media/DVD/image.jpg"
al_p4 = Image.open(filepath).resize((100, 150), Image.ANTIALIAS)
al_p4 = ImageTk.PhotoImage(al_p4)
print(filepath)

If you need to print something to a widget, it's going to depend on the kind of widget you want to use. For something small like a file path, a label would probably be good. Look at effbot's documentation for the label widget for more details.

If you want to redirect all print statements to a widget, which can be useful depending on how your GUI is designed, create a class to redirect stdout. Here's an example with a text widget:

import sys
import Tkinter

def nothing():
    print("Nothing")

class Application(Tkinter.Frame):
    def __init__(self, master = None):
        Tkinter.Frame.__init__(self, master)

        self.button = Tkinter.Button(text = "Button 1", command = nothing)
        self.button.pack()

        class StdoutRedirector(Tkinter.Text):
            def __init__(self):
                Tkinter.Text.__init__(self)
             def write(self, message):
                 printout.insert(Tkinter.END, message)
        printout = StdoutRedirector()
        printout.pack()
        sys.stdout = printout

root = Tkinter.Tk()
app = Application(root)
app.mainloop()