所以我创建了以下函数,该函数接收用户从tkinter文件浏览器中选择的图像,打开它,将其重新保存为.gif
(必需) 临时目录,然后将其设置为tkinter画布的背景:
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 :(得分:0)
您似乎试图将文件的整个路径附加到temprary目录(因此,name="{{bindThisValuePerAnswerOption}}"
代替/path/to/tmpdir/ImageName.jpg.gif
,而不是/path/to/tmpdir/Users/Name/Pictures/ImageName.jpg.gif
。
您没有指定错误发生在哪一行,但我怀疑您在尝试保存文件时遇到错误,因为这些干预目录不在存在。
考虑只获取文件的基本名称:
img.save(os.path.join(tmp, os.path.nasename(cng) + '.gif'), 'GIF')