帮我写一个打开文件对话框然后选择图片文件打开并保存到指定文件夹的代码
时间: 2024-01-21 20:01:52 浏览: 116
好的,以下是一个基于Python tkinter的简单示例代码,可以实现打开文件对话框选择图片文件并保存到指定文件夹:
```python
import tkinter as tk
from tkinter import filedialog
from PIL import Image
import os
root = tk.Tk()
root.withdraw()
# 打开文件对话框
file_path = filedialog.askopenfilename(filetypes=[("Image Files", "*.png;*.jpg;*.jpeg")])
# 读取图片文件
img = Image.open(file_path)
# 选择保存的文件夹
save_dir = filedialog.askdirectory()
# 获取图片文件名
file_name = os.path.basename(file_path)
# 拼接保存路径和文件名
save_path = os.path.join(save_dir, file_name)
# 保存图片文件
img.save(save_path)
print("图片文件已保存!")
```
这段代码与之前的代码类似,不同之处在于使用了`filedialog`模块的`askdirectory()`方法来选择保存的文件夹,并使用`os`模块来获取图片文件名和拼接保存路径和文件名。你可以根据自己的需要进行修改和扩展。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)