Problem with saving a tkinter canvas as image

206 views Asked by At

I want to save the content of a tkinter canvas as an image. I found the code specified in my save function many times before as an accepted answer in other posts. But when I'm running this code I receive an image which looks like the one below. The snippet is too small and not aligned with the canvas. How can I adapt my code?

enter image description here

import tkinter as tk
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from PIL import ImageGrab

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

# data for plots
cols = 2
x1, x2, x3, x4 = [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]
y1, y2, y3, y4 = [1, 2, 3], [1, 2, 1], [3, 2, 1], [3, 2, 3]

root = tk.Tk()
canvas = tk.Canvas(root, background="grey")
row_title = tk.Label(canvas, text="rows", font=("Arial 24 bold"), background="grey")
column_title = tk.Label(canvas, text="columns", font=("Arial 24 bold"), background="grey")

# plots
fig = plt.Figure(figsize=(5, 5))
fig.set_facecolor("grey")

plot1 = fig.add_subplot(221)
plot1.scatter(x1, y1)
plot2 = fig.add_subplot(222)
plot2.scatter(x2, y2)
plot3 = fig.add_subplot(223)
plot3.scatter(x3, y3)
plot4 = fig.add_subplot(224)
plot4.scatter(x4, y4)

chart1 = FigureCanvasTkAgg(fig, canvas)
chart1.get_tk_widget().grid(row=1, column=1)

button = tk.Button(text="Save", command=save)

canvas.grid(row=0, column=0)
row_title.grid(row=1, column=0, rowspan=2, padx=5, pady=5)
column_title.grid(row=0, column=1, columnspan=2)
button.grid(row=2, column=0)

root.mainloop()

0

There are 0 answers