2016-02-07 156 views
0

所以我创建了下面的函数,它接受用户从Tkinter的文件浏览器中选择一个图像,打开它,重新将其保存为一个.gif(这是需要)在临时目录,然后将其设置为Tkinter的画布的背景:Python的临时文件模块的临时目录发布

def background(): 
    # Create temporary directory and return path as 'tmp' 
    tmp = tempfile.mkdtemp() 
    # Ask user for image file 
    cng = filedialog.askopenfilename() 
    # Open the image using the PIL's `open` function 
    img = Image.open(cng) 
    # Supposed to save image to the `tmp` directory as a GIF 
    img.save(tmp + cng + '.gif', 'GIF') 
    # Supposed to set image file from temporary directory as background picture 
    bgpic(tmp + cng + '.gif') 

然而,每当运行上面的代码,我得到以下错误:

FileNotFoundError: [Errno 2] No such file or directory: 'var/folders/g_/099nlyhn51gf_sy21gvcp2fc0000gn/T/tmpj2z501ml/Users/Name/Pictures/ImageName.jpg.gif' 
即使我 temple.mkdtemp()创建它

显然,目录无法找到。 我在这里做错了什么导致这个错误?任何帮助,非常感谢! :)

回答

0

你似乎是想,你使用/path/to/tmpdir/Users/Name/Pictures/ImageName.jpg.gif向文件的完整路径添加到temprary目录(所以不是/path/to/tmpdir/ImageName.jpg.gif

没有指定在哪一行错误的是发生的事情,但我怀疑你要试图当保存文件的错误,因为不存在这些中间的目录

考虑只取文件的基本名称:

img.save(os.path.join(tmp, os.path.nasename(cng) + '.gif'), 'GIF')