2

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 ;)

Music Champ29
  • 67
  • 1
  • 1
  • 8
  • You may want to be a bit more clear on what you mean by "return the file path of the image." Do you mean return it to another function? Or print the file path to a widget to make it viewable to the user? Or something else entirely? Basically, more information would be helpful. – Gustav Sep 01 '14 at 23:53
  • 1
    It seems the `filename` can be retrieved from the result of `Image.open`, but is lost when you `resize` the image or when you turn it into a `PhotoImage`. – tobias_k Sep 02 '14 at 11:28

2 Answers2

1

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()
Gustav
  • 688
  • 5
  • 12
0

I'm new to coding, so I'll try the best I can =) Quick answer: You need to use .filename in the PIL object (Don't works on TK object)

#This is the image: al_p4 = Image.open("Media/DVD/image.jpg").resize((100, 150), Image.ANTIALIAS)

#This is to show in Tkinter, Notice I added ..._TK al_p4_TK = ImageTk.PhotoImage(al_p4)

#This is the filepath I think you want: print(al_p4.filename)

V-cash
  • 330
  • 3
  • 14