如何获取 tkinter 的屏幕截图 window

How to get the screenshot of a tkinter window

我正在尝试构建一个程序来获取我想要的文本的放大照片,为此我决定使用 tkinter、win32gui 和 pygetwindow从已经提出的堆栈溢出问题中获取一些提示后,模块出现以下问题:

(1)我不知道如何获取我创建的 tkinter window 的 hwnd 值。

(2)我无法获取 hwnd 值,即使我知道如何获取它,因为 window 是在完整代码具有 运行 之后创建的。

所以请给我建议解决问题的方法

这是我的代码:

from tkinter import *
import win32gui
import pygetwindow as gw

#making the tkinter window
root = Tk()
root.title('DaysLeft')

#getting all the windows with their hwnd values
hwnd=gw.getAllWindows()
print(hwnd)

win32gui.SetForegroundWindow(hwnd)
bbox = win32gui.GetWindowRect(hwnd)
img = ImageGrab.grab(bbox)
img.show()

mainloop()

上面的代码给出的错误低于预期:.

 line 26, in <module>
    win32gui.SetForegroundWindow(hwnd)
TypeError: The object is not a PyHANDLE object

您可以使用 PIL 进行屏幕截图,并使用 win32guipygetwindow 获取 windows 位置。

通过说

安装PIL
pip install Pillow

那么您的工作代码将是:

from tkinter import *
from win32gui import FindWindow, GetWindowRect
import pygetwindow as gw
from PIL import ImageGrab

def ss():
    win = gw.getWindowsWithTitle('DaysLeft')[0]
    winleft = win.left+9
    wintop = win.top+38 #change 38 to 7 to not capture the titlebar
    winright = win.right-9
    winbottom = win.bottom-9
    final_rect = (winleft,wintop,winright,winbottom)
    img = ImageGrab.grab(final_rect)
    img.save('Required Image.png')
#making the tkinter window
root = Tk()
root.title('DaysLeft')

root.after(3000,ss)

root.mainloop()

为什么我要从像素中减去一些数量?这是因为,windows 对 windows 有像投影效果这样的装饰,它们也是 windows 的一部分,并将包含在屏幕截图中,所以我用它来摆脱那些额外的像素。

或者如果您仍然不愿意使用 win32gui 那么,将函数更改为:

from win32gui import FindWindow, GetWindowRect
from PIL import ImageGrab
......
def ss():
    win = FindWindow(None, 'DaysLeft')
    rect = GetWindowRect(win)
    list_rect = list(rect)
    list_frame = [-9, -38, 9, 9] #change -38 to -7 to not capture the titlebar
    final_rect = tuple((map(lambda x,y:x-y,list_rect,list_frame))) #subtracting two lists

    img = ImageGrab.grab(bbox=final_rect)
    img.save('Image.png')

什么是after方法?它只是在 3000 毫秒(即 3 秒)后调用该函数。我们基本上是在给系统一些时间来构建 GUI 和捕获屏幕截图。

希望对您有所帮助,如有任何错误或疑问,请告诉我。

干杯