简体   繁体   English

ImageGrab.grab 不是获取 tkinter 窗口的小部件,而是获取其下的屏幕区域

[英]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.尝试通过以下代码在 tkinter 窗口中捕获小部件的图像,但只需获取 tkinter 窗口下的屏幕区域。

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) .如果第# sleep(1)替换为sleep(1) Had been tried method update or update_idletasks , all got same results.已经尝试过方法updateupdate_idletasks ,都得到了相同的结果。

Is there any method to finalize tkinter window immediately ?是否有任何方法可以立即完成 tkinter 窗口? 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.或者我走错了路,欢迎提出任何建议。

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.把它放在一个函数中,并after这里利用after方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM