1

I have this code taken from the internet(I can't find the link to show it to you). It generates random rectangles. What I want to do is to save this drawing as a png. Actually, I want to convert the white pixels(color of background more precisely) to transparent pixels, and to have a png with only the rectangles, no background color. But I first wanted to make sure I can save it as a simple png. The save button, when clicked, should do the saving.

import tkinter as tk
import random

class GUI(tk.Frame):
    def __init__(self, root):
        tk.Frame.__init__(self, root)
        self.root = root
        self.canvas = tk.Canvas(self, width=400, height=400, background="#FFFFFF")
        self.xsb = tk.Scrollbar(self, orient="horizontal", command=self.canvas.xview)
        self.ysb = tk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
        #self.button = tk.Button(root, text="save as", command=self.save)
        #self.button.pack()
        self.canvas.configure(yscrollcommand=self.ysb.set, xscrollcommand=self.xsb.set)
        self.canvas.configure(scrollregion=(0, 0, 1000, 1000))
        self.xsb.grid(row=1, column=0, sticky="ew")  # stick East and West
        self.ysb.grid(row=0, column=1, sticky="ns")  # stick North and South
        self.canvas.grid(row=0, column=0, sticky="nsew")
        # weight of zero means the column will not grow if there's extra space =>
        # => we need canvas to have 1 on row and col
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        self.plot_random_rectangles()

    def plot_random_rectangles(self):
        for n in range(50):
            x0 = random.randint(0, 900)
            y0 = random.randint(50, 900)
            x1 = x0 + random.randint(50, 100)
            y1 = y0 + random.randint(50,100)
            color = ("red", "orange", "yellow", "green", "blue")[random.randint(0,4)]
            self.canvas.create_rectangle(x0, y0, x1, y1, outline="black", fill=color, activefill="black", tags=n)
        self.canvas.create_text(50,10, anchor="nw", text="Click and drag to move the canvas\nScroll to zoom.")

The problem is, I have tried multiple save functions found on the internet, three of them I will put at the end. None of them work. I also stumbled into the error: "OSError: Unable to locate Ghostscript on paths". I can't find Ghostscript on my Windows10, so I was wondering if I can manage what I want in other ways. This is crucial for my project, which is to generate a drawing of a tree to use in games(hence the need for transparent background). Any help is appreciated! I will put some of the save functions down:

    def save(self):
    ps = self.canvas.postscript(colormode='color')
    img = Image.open(io.BytesIO(ps.encode('utf-8')))
    img.save('test.jpg')

def getter(self):
    x = self.root.winfo_rootx() + self.canvas.winfo_x()
    y = self.root.winfo_rooty() + self.canvas.winfo_y()
    x1 = x + self.canvas.winfo_width()
    y1 = y + self.canvas.winfo_height()
    ImageGrab.grab().crop((x, y, x1, y1)).save("test.png")

def save_as_png(self):
    # save postscipt image
    self.canvas.postscript(file='test.eps')
    # use PIL to convert to PNG
    img = Image.open('test' + '.eps')
    img.save('test' + '.png', 'png')

P.S: I've only started recently to play with tkinter canvas, so I am a beginner.

  • Have you seen this answer to a similar question? https://stackoverflow.com/a/38645917/7432 – Bryan Oakley Dec 19 '21 at 01:25
  • @BryanOakley yes and I can't seem to make it work with this code unfortunately. I didn't include in the code, but I also have a zoom in / zoom out function. What that code from the link does: it takes a screenshot of my canvas, but it takes it bad for 2 reasons: 1. It also shows some of my IDE/desktop (it doesn't crop good) 2. It doesn't take a screenshot of the whole image, just the zoomed in image. – NVPH_Studio Dec 19 '21 at 02:15

0 Answers0