Python tkinter 实现另存为图片
时间: 2023-11-29 17:53:34 浏览: 134
要在Python tkinter中实现另存为图片功能,可以使用Python Imaging Library(PIL)。
首先,导入必要的库:
```python
from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageDraw
```
然后,创建一个画布并绘制一些形状:
```python
# 创建画布
canvas_width = 400
canvas_height = 400
canvas = Canvas(root, width=canvas_width, height=canvas_height, bg='white')
canvas.pack()
# 绘制一个圆形和一个矩形
canvas.create_oval(50, 50, 150, 150, fill='red')
canvas.create_rectangle(200, 200, 300, 300, fill='blue')
```
接下来,定义一个函数来保存画布中的内容为图片:
```python
def save_canvas():
# 获取画布截图
x = root.winfo_rootx() + canvas.winfo_x()
y = root.winfo_rooty() + canvas.winfo_y()
x1 = x + canvas.winfo_width()
y1 = y + canvas.winfo_height()
image = ImageGrab.grab((x, y, x1, y1))
# 弹出文件对话框,选择保存位置和文件名
file_path = filedialog.asksaveasfilename(defaultextension='.png')
if file_path:
image.save(file_path)
```
最后,创建一个按钮来触发保存函数:
```python
# 创建按钮
save_btn = Button(root, text='Save as Image', command=save_canvas)
save_btn.pack()
```
完整代码如下:
```python
from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageDraw, ImageGrab
root = Tk()
root.title('Save Canvas as Image')
root.geometry('400x450')
# 创建画布
canvas_width = 400
canvas_height = 400
canvas = Canvas(root, width=canvas_width, height=canvas_height, bg='white')
canvas.pack()
# 绘制一个圆形和一个矩形
canvas.create_oval(50, 50, 150, 150, fill='red')
canvas.create_rectangle(200, 200, 300, 300, fill='blue')
def save_canvas():
# 获取画布截图
x = root.winfo_rootx() + canvas.winfo_x()
y = root.winfo_rooty() + canvas.winfo_y()
x1 = x + canvas.winfo_width()
y1 = y + canvas.winfo_height()
image = ImageGrab.grab((x, y, x1, y1))
# 弹出文件对话框,选择保存位置和文件名
file_path = filedialog.asksaveasfilename(defaultextension='.png')
if file_path:
image.save(file_path)
# 创建按钮
save_btn = Button(root, text='Save as Image', command=save_canvas)
save_btn.pack()
root.mainloop()
```
阅读全文