如何获取Tkinter窗口的屏幕截图

时间:2020-09-06 09:23:00

标签: python tkinter win32gui

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

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

(2)即使在完整的代码运行后创建窗口时,我也无法获得hwnd值。

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

这是我的代码:

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

1 个答案:

答案 0 :(得分:0)

您可以使用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()

为什么我要从像素中减去一些量?这是因为,窗口对窗口具有类似阴影效果的装饰,这也是窗口的一部分,将包含在屏幕截图中,所以我用它来去除那些多余的像素。

或者,如果您仍然不愿意使用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和捕获屏幕截图。

希望有帮助,请让我知道是否有任何错误或疑问。

欢呼