PIL没有读取tkFileDialog?

时间:2016-02-01 03:24:15

标签: python tkinter

files = tkFileDialog.askopenfile(mode='rb',filetypes=fileTypes,initialdir = direc,multiple=False,parent = root,title = 'Choose an Image')
    framing = Toplevel()
    framing.title("Framing Menu")
    scroll = Scrollbar(framing)
    scroll.pack(side=RIGHT,fill=Y)
    imLabel = Label(framing)
    imLabel.pack(side=RIGHT)
    image = ImageTk.PhotoImage(PIL.Image.open(files))
    imlabel2 = Label(framing,image=image)
    imlabel2.image = image
    imlabel2.pack(side=RIGHT)

当我使用文件对话框从用户获取文件,并尝试使用PIL打开它时,我收到此错误:

IOError: cannot identify image file <open file u'C:/Users/Alec/Pictures/california-county-map.gif', mode 'r' at 0x000000000A93A030>

california-county-map.gif是我正在使用的测试图片,PIL显然无法读取它,这里发生了什么?

2 个答案:

答案 0 :(得分:1)

问题是ImageTk.PhotoImage()期待一个文件名,而是一个打开的文件,所以只需更改:

ImageTk.PhotoImage(PIL.Image.open(files))

为:

ImageTk.PhotoImage(file=files) #need the 'file=' to specify you are using an already opened file

编辑:

另一种解决方案是从用户处获取文件名,然后使用PIL打开文件,您需要使用askopenfilename而不是askopenfile

files = tkFileDialog.askopenfile(filetypes=fileTypes,initialdir = direc,multiple=False,parent = root,title = 'Choose an Image')
...
image = ImageTk.PhotoImage(PIL.Image.open(files))

答案 1 :(得分:0)

Here所述, 你可以做ImageTk.PhotoImage(file = filename,size = None,** kw)。所以你可以先得到文件名:

import Tkinter
import tkFileDialog
from PIL import ImageTk
root = Tkinter.Tk()
fileTypes = [ ('All','*'), ("GIF","*.gif")]
filename = tkFileDialog.askopenfilename(filetypes=fileTypes,initialdir = 't:/',multiple=False,parent = root,title = 'Choose an Image')
image = ImageTk.PhotoImage( file = filename)