【问题标题】:How to get the screenshot of a tkinter window如何获取 tkinter 窗口的屏幕截图
【发布时间】:2020-09-06 09:23:00
【问题描述】:

我正在尝试构建一个程序,它可以让我获得我想要的文本的放大照片,为此我决定使用 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

【问题讨论】:

    标签: python tkinter win32gui


    【解决方案1】:

    您可以使用PIL 进行截图,使用win32guipygetwindow 获取窗口位置。

    通过说安装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 对窗口有阴影效果等装饰,它们也是窗口的一部分,将包含在屏幕截图中,所以我用它来去除那些额外的像素。

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

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

    干杯

    【讨论】:

    • 感谢您的回答,我先尝试了第二种方法,发现以下错误,您在减法时命名了list1和list2,在分配时使用了list_frame和list_rect。请检查这是一个错误还是故意的。
    • 我收到以下错误:“第 25 行,在 rect = win32gui.GetWindowRect(win) pywintypes.error: (1400, 'GetWindowRect', 'Invalid window handle.')”
    • 我尝试了您的第一种方法,但我认为由于窗口尚未激活,因此会出现以下错误: Traceback (last recent call last): File "C:/Users/SAMSUNG/PycharmProjects /daysleftproject/main.py",第 24 行,在 中 win = gw.getWindowsWithTitle('window')[0] IndexError: list index out of range
    • @RudraanshPatel 我已经更新了代码并修复了错误,以便它适用于您的代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多