我想截取 python tkinter 窗口的屏幕截图(不是整个计算机屏幕)。我应用了以下代码:
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)" 定义的窗口的屏幕截图 但是,我正在捕捉整个屏幕。
有人可以让我知道我们如何在 python 中解决这个问题吗?
答案 0 :(得分:1)
由于您使用的是 Windows,因此您应该能够使用 win32 API,
与此相反,您可以使用更简单的解决方案,例如 PyScreenshot
以下面的代码为例:
from pyscreenshot import grab
im = grab(bbox=(100, 200, 300, 400))
im.show()
“ 如您所见,您可以使用 bbox 截取坐标为 (100, 200) 且宽度为 300、高度为 400 的屏幕截图。
这需要你事先知道窗口的位置——我相信你可以在 Tkinter 中做到这一点。”
我从之前的 SO 问题中找到了这些信息。这是另一个可能对您有所帮助的片段。
这是在 win32 上使用 PIL 的方法。给定一个窗口句柄 (hwnd),您应该只需要最后 4 行代码。前面只是搜索标题中带有“firefox”的窗口。由于 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)
我希望这会有所帮助,有时只需要一个好的谷歌搜索。如果这对您有帮助,请选择此作为正确答案
根据窗口的内容,您可以使用它 - 如果它是绘图。
“您可以生成一个 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
答案 1 :(得分:1)
您需要为屏幕截图定义矩形
而不是myScreenshot = pyautogui.screenshot()
使用以下内容代替它:
myScreenshot = pyautogui.screenshot(region=(0,0, 300, 400))
这 4 点描述了您想要截图的位置
答案 2 :(得分:1)
您可以获取画布的区域并将它们传递给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))