2014-09-01 388 views
0

我在tkinter中有一個名爲al_p4的PhotoImage,但我希望能夠打印圖像的文件路徑。任何人都可以幫忙這裏是我的代碼:Python Tkinter - 從PhotoImage查找圖像文件路徑

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

在此先感謝球員;)

+0

您可能希望更清楚地說明「返回圖像的文件路徑」的含義。你的意思是返回到另一個功能?或者將文件路徑打印到一個小部件以使其可以被用戶看到?還是其他什麼東西?基本上,更多的信息會有所幫助。 – Gustav 2014-09-01 23:53:09

+0

Thanks @Gustav我編輯了我的問題。 – 2014-09-02 11:19:05

+1

看起來'filename'可以從'Image.open'的結果中找到,但是當你調整圖像的大小或者將它變成PhotoImage時會丟失。 – 2014-09-02 11:28:28

回答

1

因爲我仍然有麻煩正好解釋你的意思,這裏是關於如何去打印四種不同的答案。

如果你只需要打印出來的道路永遠是恆定的,使用方法:

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

如果您需要打印的東西,路徑會有所不同,請嘗試:

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

如果你需要打印一些東西到一個小部件,它將取決於你想要使用的小部件的種類。對於像文件路徑那樣小的東西,標籤可能會很好。請參閱effbot's documentation for the label widget瞭解更多詳情。

如果您想要將所有打印語句重定向到一個小部件,這取決於GUI的設計方式,這可能很有用,請創建一個類來重定向stdout。下面是一個帶有文本小部件的示例:

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