截取 python tkinter window 的屏幕截图(不是整个计算机屏幕)

Take screenshot of python tkinter window (NOT entire computer screen)

我想截取 python tkinter window 的屏幕截图(不是整个计算机屏幕)。我应用了以下代码:

import pyautogui
import tkinter as tk

root= tk.Tk()

# Define tkinter window 
canvas1 = tk.Canvas(root, width = 300, height = 300)
canvas1.pack()

# Define fuction to take screenshot
def takeScreenshot ():
    
    myScreenshot = pyautogui.screenshot()
    myScreenshot.save('screenshot.png')


# Define fuction to take screenshot
myButton = tk.Button(text='Take Screenshot', command=takeScreenshot, bg='green',fg='white',font= 10)
canvas1.create_window(150, 150, window=myButton)

root.mainloop()

我只想抓取由 定义的 window 的屏幕截图"tk.Canvas(root, width = 300, height = 300)" 但是,我正在捕获整个屏幕。

有人可以告诉我我们如何在 python 中解决这个问题吗?

因为你在 windows 你应该可以使用 win32 API,

与此相反,您可以使用更简单的解决方案,例如 PyScreenshot

以下面的代码为例:


from pyscreenshot import grab

im = grab(bbox=(100, 200, 300, 400))
im.show()

“ 如您所见,您可以使用 bbox 截取 co-ordinates (100, 200) 处的屏幕截图,宽度为 300,高度为 400.

这需要你事先知道 windows 的位置——我相信你可以在 Tkinter 中做到这一点。”

我从之前的 SO 问题中找到了这些信息。这是另一个可能对您有帮助的片段。

以下是在 win32 上使用 PIL 的方法。给定一个 window 句柄 (hwnd),您应该只需要最后 4 行代码。前面只是搜索标题中带有“firefox”的window。由于 PIL 的源代码可用,您应该能够浏览 ImageGrab.grab(bbox) 方法并找出实现此目的所需的 win32 代码。


from PIL import ImageGrab
import win32gui

toplist, winlist = [], []
def enum_cb(hwnd, results):
    winlist.append((hwnd, win32gui.GetWindowText(hwnd)))
win32gui.EnumWindows(enum_cb, toplist)

firefox = [(hwnd, title) for hwnd, title in winlist if 'firefox' in title.lower()]
# just grab the hwnd for first window matching firefox
firefox = firefox[0]
hwnd = firefox[0]

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

我找到的建议包括: How to do a screenshot of a tkinter application?

How to Get a Window or Fullscreen Screenshot in Python 3k? (without PIL)

我希望这对您有所帮助,有时只需要一个好的 google 搜索。如果对您有帮助,请select将此作为正确答案

编辑

根据 window 的内容,如果是绘图,您可以使用它。

“您可以生成一个 postscript 文档(以输入其他工具:ImageMagick、Ghostscript 等)”


from Tkinter import *
root = Tk()
cv = Canvas(root)
cv.create_rectangle(10,10,50,50)
cv.pack()
root.mainloop()

cv.update()
cv.postscript(file="file_name.ps", colormode='color')

root.mainloop()

如果您正在尝试保存绘图,请查看此内容https://www.daniweb.com/programming/software-development/code/216929/saving-a-tkinter-canvas-drawing-python

您需要为屏幕截图定义矩形

而不是myScreenshot = pyautogui.screenshot()

使用以下内容代替它:

myScreenshot = pyautogui.screenshot(region=(0,0, 300, 400))

这4点描述了你想要截图的地方

https://pyautogui.readthedocs.io/en/latest/screenshot.html

您可以获得 canvas 的区域并将它们传递给 screenshot():

def takeScreenshot():
    # get the region of the canvas
    x, y = canvas1.winfo_rootx(), canvas1.winfo_rooty()
    w, h = canvas1.winfo_width(), canvas1.winfo_height()
    pyautogui.screenshot('screenshot.png', region=(x, y, w, h))