2016-02-07 72 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')