Jason Yang
Jason Yang

Reputation: 13051

ImageGrab.grab not get widget of tkinter window, but screen area under it

Try to capture the image of a widget in tkinter window by following code, but just get the screen area under tkinter window.

import ctypes
import platform
from time import sleep
import tkinter as tk

from PIL import ImageGrab

if platform.system() == "Windows" and platform.release() == "10":
    ctypes.windll.shcore.SetProcessDpiAwareness(1)

root = tk.Tk()
root.geometry("+0+0")

var = tk.StringVar()
var.set("Hello World")
entry = tk.Entry(root, width=40, bg='green', takefocus=False, textvariable=var)
entry.pack()

root.update()
# sleep(1)

x, y = entry.winfo_rootx(), entry.winfo_rooty()
width, height = entry.winfo_width(), entry.winfo_height()

im = ImageGrab.grab(bbox=(x, y, x+width, y+height))    # Grab image on screen
im.show()

root.mainloop()

It will be OK if line # sleep(1) replaced by sleep(1). Had been tried method update or update_idletasks, all got same results.

Is there any method to finalize tkinter window immediately ? So I don't need to sleep one second each time to grap image of a widget. Or I get wrong way to go it, any suggestion is welcome.

Upvotes: 0

Views: 534

Answers (1)

Delrius Euphoria
Delrius Euphoria

Reputation: 15098

It is obvious right? It needs to take some time to show the window but the screenshot is captured quite quickly. What do I suggest? Put it inside a function and take advantage of the after method here.

def screenshot():
    im = ImageGrab.grab(bbox=(x, y, x+width, y+height))    # Grab image on screen
    im.show()

root.after(1000,screenshot) # Depending on the time required to take show the window

Upvotes: 2

Related Questions