dominik findeisen
dominik findeisen

Reputation: 62

Weird things happening when using ImageGrab.grab()

I have some code:

from tkinter import *
from tkinter import *
from PIL import Image, ImageGrab

root = Tk()


def capture():
    x0 = canvas.winfo_rootx()
    y0 = canvas.winfo_rooty()
    x1 = x0 + canvas.winfo_width()
    y1 = y0 + canvas.winfo_height()

    im = ImageGrab.grab((x0, y0, x1, x2))
    im.save('mypic.png')  # Can also say im.show() to display it


canvas = Canvas(root, bg='red')
canvas.pack(padx=10, pady=10)

e = Entry(root)

canvas.create_window(canvas.canvasx(100), canvas.canvasy(100), window=e)

Button(root, text='Click a pic', command=capture).pack()

root.mainloop()

It makes mypic:

enter image description here

Which is part of my background But i want it to make:enter image description here

Which is a screenshot of my screen.

I tried changing other parameters like include_layeder_windows, but it didn't change anything. My problem is that grab() returns my background instead of my screen.

Upvotes: 1

Views: 169

Answers (1)

Piotr Findeisen
Piotr Findeisen

Reputation: 20770

It seems you're using Mac OS. In Mac, an application by default cannot grab contents of other application's window. When trying to do so, it will grab the desktop background only. This could perhaps be observed e.g. when sharing screen over e.g. Zoom, without giving Zoom proper permissions.

To fix that, you need to go to "System Preferences" > "Privacy" > "Privacy" > "Screen Recording" and add your application there.

Upvotes: 1

Related Questions