我可以在 Python Tkinter Canvas 上对图像进行“屏幕截图"并将其保存在文件中吗? [英] Can I do 'screenshot' of image on the Python Tkinter Canvas and save it in the file?
问题描述
我编写了在 Python tkinter Canvas 中制作图像的程序,但我不知道如何保存我创建的图像.它可以是 png、gif 任何东西,但我想保存我的作品!
I made program to make images in Python tkinter Canvas, but I have no idea how to save images I created. It can be png, gif, anything, but I want to save my work!
这是我的代码:
import tkinter
from PIL import Image, ImageGrab
paint = tkinter.Tk()
paint.title('paint')
canvas = tkinter.Canvas(paint, width=1100, height=1000, bd=0, highlightthickness=0)
canvas.pack()
def capture(event):
x0 = canvas.winfo_rootx()
y0 = canvas.winfo_rooty()
x1 = x0 + canvas.winfo_width()
y1 = y0 + canvas.winfo_height()
im = ImageGrab.grab((100, 0, 1100, 1000))
im.save('mypic.png')
canvas.mainloop()
我删除了一些代码,因为它并不重要.但它在没有我的画布的情况下制作了一个截图!
I deleted some of my code because it isn't important. But it makes a screenshot without my canvas!
推荐答案
由于没有提供代码,我将举一个例子来说明这是如何完成的.默认情况下,tkinter 中有一些方法可以为您执行此操作.因此,为了截取屏幕截图,我们将使用 PIL
.
Since there is no code provided, I will give you an example on how this is done. By default there is methods within tkinter that does this for you. So for taking screenshots, we will use PIL
.
- 从安装
PIL
开始:
pip install Pillow
- 代码如下:
from tkinter import *
from PIL import Image, ImageGrab
root = Tk()
def capture():
x0 = canvas.winfo_rootx()
y0 = canvas.winfo_rooty()
x1 = x0 + canvas.winfo_width()
y1 = y0 + canvas.winfo_height()
im = ImageGrab.grab((x0, y0, x1, y1))
im.save('mypic.png') # Can also say im.show() to display it
canvas = Canvas(root,bg='red')
canvas.pack(padx=10,pady=10)
e = Entry(root)
canvas.create_window(canvas.canvasx(100),canvas.canvasy(100),window=e)
Button(root,text='Click a pic',command=capture).pack()
root.mainloop()
没什么太复杂的,坐标如下ImageGrab.grab((left,upper,right,lower))
,这是一张可以帮助你更好地理解侧面的图片:
Nothing too complicated, the coordinates work as follows ImageGrab.grab((left,upper,right,lower))
, here is an image that might help you understand the sides better:
注意(根据 WinEunuuchs2Unix):Linux 不支持 ImageGrab
,对于替代方案,请使用 ImageGrab 替代方案linux
Note(as per WinEunuuchs2Unix): ImageGrab
is not supported with Linux, for alternatives use ImageGrab alternative in linux
这篇关于我可以在 Python Tkinter Canvas 上对图像进行“屏幕截图"并将其保存在文件中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!