I have the following problem: I have a Tkinter Canvas, on which I want to draw. The canvas is surrounded by some border, to indicate where to draw and where not. I want to be able to export the canvas image as a png. However, when I export it, it seems that the cropping is not correct. If I move the whole UI (or even when it is initialized), I see stuff behind the UI from other windows, or I see the left and upper part of the gray boundary, but on the other hand I do not see anything from the lower right corner. Can someone help me with the correct cropping?
import tkinter as tk
from PIL import ImageGrab
class DrawingCanvas(tk.Canvas):
def __init__(self, master=None):
super().__init__(master, width=500, height=500)
self.bind("<ButtonPress-1>", self.start_draw)
self.bind("<B1-Motion>", self.draw)
self.bind("<ButtonRelease-1>", self.end_draw)
self.bind("<ButtonPress-3>", self.export_canvas_image)
self.drawn_lines = []
def start_draw(self, event):
self.line_start = (event.x, event.y)
def draw(self, event):
current_line = self.create_line(self.line_start[0], self.line_start[1], event.x, event.y, fill="black", width=5)
self.line_start = (event.x, event.y)
self.drawn_lines.append(current_line)
def end_draw(self, event):
self.line_start = None
def export_canvas_image(self, event):
x = self.winfo_rootx()
y = self.winfo_rooty()
width = self.winfo_width()
height = self.winfo_height()
req_width = self.winfo_reqwidth()
req_height = self.winfo_reqheight()
# Calculate the size of the border and other decorations
border_width = (width - req_width) // 2
titlebar_height = height - req_height - border_width
# Adjust the coordinates and dimensions to exclude the border and other decorations
x += border_width
y += titlebar_height
width -= 2 * border_width
height -= titlebar_height + border_width
ImageGrab.grab().crop((x, y, x+width, y+height)).save("temp.png")
if __name__ == "__main__":
root = tk.Tk()
root.configure(bg="black")
frame = tk.Frame(root, bg="black", bd=10)
frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
canvas = DrawingCanvas(frame)
canvas.pack(fill=tk.BOTH, expand=True)
root.mainloop()
I tried to get a screenshot of the whole monitor and then crop it to only get the canvas. Did not work.