我是一個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()
我甚至通過創建文件名的屬性嘗試過,但沒有幫助.......
感謝您的回答。我也需要其他回調中的圖片。我怎樣才能做到這一點? – bistaumanga
'self.img'被'setImage(self)'設置一次後,它被打開後,它應該總是可用於其他回調作爲'self.img'。 –
非常感謝您的指導。我的問題解決了。 – bistaumanga