0

I managed to save the content of an tkinter canvas to an image like in this post How can I convert canvas content to an image?. But this seems to work only if I add the line of code ctypes.windll.shcore.SetProcessDpiAwareness(1) for adjusting the resolution (Picture 1). Unfortunately, the resolution stays the same. If I don't use this code the image contains only a part of the canvas with some part of the background (Picture 2).

I couldn't find any further information on how ctypes.windll.shcore.SetProcessDpiAwareness(1) works exactly. Is there a way to increase the resolution with this or is there another way?

Picture 1

Picture 2

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

def save():
    x = canvas.winfo_rootx() + canvas.winfo_x()
    y = canvas.winfo_rooty() + canvas.winfo_y()
    x1 = x + canvas.winfo_width()
    y1 = y + canvas.winfo_height()
    ImageGrab.grab().crop((x, y, x1, y1)).save("insert file path here")

# 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()
ctypes.windll.shcore.SetProcessDpiAwareness(1)
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()
Plantz
  • 97
  • 7

0 Answers0