Theres an way easier way to do that, without any imagegrab or anything other.
You can grab every pixel from the canvas and then draw it to image. Just like this program.
It may be kinda slow if you have a lot of things of canvas, But atleast, it doesnt use ghostscript tho, And you can just keep the findobjat
, save
functions.
from tkinter import *
from PIL import Image
import webcolors
drawing = False
def findobjat(x,y,C):
obj = C.find_overlapping(x,y,x,y)
if len(obj) == 0:
return (255,255,255)
color = C.itemcget(obj[-1],"fill")
if type(color) == str:
color = webcolors.name_to_rgb(color)
return color
def save(C,w,h):
im = Image.new("RGB",(w,h))
for x in range(w):
for y in range(h):
color = findobjat(x,y,C)
im.putpixel((x,y),color)
return im
def postsave():
save(C,200,200).save("image.png")
def drawstart(event):
global drawing
drawing = True
def drawstop(event):
global drawing
drawing = False
def draw(event):
if drawing:
C.create_oval(event.x-5,event.y-5,event.x+5,event.y+5,fill = "black")
root = Tk()
root.geometry("200x200")
C = Canvas(root,bg = "white",width = 200,height = 200)
C.bind("<Button-1>",drawstart)
C.bind("<ButtonRelease-1>",drawstop)
C.bind("<B1-Motion>",draw)
button = Button(root,text = "Save image",command = postsave)
button.pack()
C.pack()
root.mainloop()