2013-01-05 27 views
0

我是一個Python初學者。我正在編寫一個簡單的GUI代碼,其中有一個菜單項「打開」,當點擊時請求圖像文件與tkFileDialog。它可以很好地讀取文件名和路徑。我想要返回文件名以便圖像可以在tkinter Label中打開和顯示。但我不知道如何返回文件名。錯誤返回文件名讀取由tkFileDialog從Python中的菜單回調

這裏是我的代碼

from Tkinter import Frame, Tk, Label, Text, Menu, END, BOTH, StringVar 
from PIL import ImageTk, Image 
import numpy 
import tkFileDialog 

class DIP(Frame): 
    def __init__(self, parent): 
     Frame.__init__(self, parent) 
     self.parent = parent   
     self.initUI() 

    def initUI(self): 

     self.parent.title("DIP Algorithms- Simple Photo Editor") 
     self.pack(fill=BOTH, expand=1) 

     menubar = Menu(self.parent) 
     self.parent.config(menu=menubar) 
     fileMenu = Menu(menubar) 
     self.fn='' 
     fileMenu.add_command(label="Open", command=self.onOpen) 
     menubar.add_cascade(label="File", menu=fileMenu) 
     print self.fn #prints nothing here 
     #self.img=Image.open(self.fn) 


    def onOpen(self): 

     ftypes = [('Image Files', '*.tif *.jpg *.png')] 
     dlg = tkFileDialog.Open(self, filetypes = ftypes) 
     filename = dlg.show() 
     self.fn=filename 
     print self.fn #prints filename with path here 


    def onError(self): 
     box.showerror("Error", "Could not open file")  

def main(): 

    root = Tk() 
    ex = DIP(root) 
    root.geometry("1280x720") 
    root.mainloop() 


if __name__ == '__main__': 
    main() 

我甚至通過創建文件名的屬性嘗試過,但沒有幫助.......

回答

1

更仔細你的代碼。您在onOpen()之前運行initUI(),然後您未運行initUI(),該設置在設置self.fn後設置圖像。

要解決這個問題,你需要將你的代碼,改變圖像標籤到另一個功能類,像這樣:然後

def setImage(self): 
    print self.fn #prints something now! 
    self.img=Image.open(self.fn) 

,在onOpen()最後,你需要調用這個函數。

def onOpen(self): 
    ... 
    self.setImage() 
+0

感謝您的回答。我也需要其他回調中的圖片。我怎樣才能做到這一點? – bistaumanga

+1

'self.img'被'setImage(self)'設置一次後,它被打開後,它應該總是可用於其他回調作爲'self.img'。 –

+0

非常感謝您的指導。我的問題解決了。 – bistaumanga

1

此行爲是預期的。當你print self.fninitUI用戶還沒有選擇一個文件。當您在onOpen中打印時,用戶選擇了一個文件,因此它顯示正確。 self.fn確實設置正確,你只是打印它太早。

如果要顯示圖像,請在用戶選擇文件後再執行此操作。

def onOpen(self): 
    ftypes = [('Image Files', '*.tif *.jpg *.png')] 
    dlg = tkFileDialog.Open(self, filetypes = ftypes) 
    filename = dlg.show() 
    self.fn = filename 
    if self.fn: # If a file was selected 
     # Display image in label/call display function 
+0

感謝您的答案。我還需要其他回調中顯示的圖像。我怎樣才能做到這一點? – bistaumanga

相關問題