tkinter screenshot with mss not working as expected

160 Views Asked by At

essentially the problem is: I want to take a screenshot of my tkinter canvas. Unfortunately I am not able to understand PIL, so don't gaslight me with Pillow or ImageGrab please.

from mss import mss

def test_shot(self):
    with mss() as sct:
        filename = sct.shot(mon=1, output="E:/project/screenshots/test_output.png")

So this actually takes a screenshot of the whole screen, in a sense that is suboptimal and blunt, But it doesn't screenshot the tkinter gui(root:frame:canvas;labels,...) and instead screenshots what is behind my tkinter gui(the code in idle and also console).

So basically my questions are: 1st Is there a way to take screenshot of the whole canvas or parts of it? 2nd Why does the screenshot show everything except my program? enter image description here

Edit: so this is how I call the function for testing purposes: shortened code

Edit 2: whenever I use mytk.update() or canvas/self.graphs.update() , it gets transparent test output

1

There are 1 best solutions below

2
On

You can use .grab() to capture part of the screen:

from mss import mss, tools

...

def test_shot(self):
    # self.graphs is the canvas object
    # make sure it is updated
    self.graphs.update()
    with mss() as sct:
        monitor = {
            "top": self.graphs.winfo_rooty(),
            "left": self.graphs.winfo_rootx(),
            "width": self.graphs.winfo_width(),
            "height": self.graphs.winfo_height(),
            "mon": 1
        }
        # grab the image of the specified region
        img = sct.grab(monitor)
        # save the image to file
        tools.to_png(img.rgb, img.size, output="test_output.png")