繁体   English   中英

截取 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()

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

有人可以让我知道我们在 python 中如何处理这个问题吗?

由于您在 windows 上,您应该能够使用 win32 API,

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

以下面的代码为例:


from pyscreenshot import grab

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

“ 如您所见,您可以使用 bbox 截取坐标为 (100, 200) 且宽度为 300、高度为 400 的屏幕截图。

这需要您事先了解 windows 的 position - 我相信您可以在 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()

我发现的建议包括: 如何截取 tkinter 应用程序?

如何在 Python 3k 中获取 Window 或全屏截图? (无 PIL)

我希望这会有所帮助,有时只需要一个好的谷歌搜索。 如果这对您有帮助,请 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))

暂无
暂无

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

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