2

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!

This is my code:

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!

Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46

1 Answers1

4

Since there is no code provided, I will give you an example on how this is done. By default there is no methods within tkinter that does this for you. So for taking screenshots, we will use PIL.

  • Start by installing PIL:
pip install Pillow
  • The code is as follows:
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()

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:

enter image description here

Note(as per WinEunuuchs2Unix): ImageGrab is not supported with Linux, for alternatives use ImageGrab alternative in linux


Update(as per Carsten Fuchs): ImageGrab is now supported with Linux, might want to update the library first

Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46