繁体   English   中英

如何捕获 tkinter window 的屏幕截图并将其存储到文件中?

[英]How to capture screenshot of tkinter window and store it to file?

我正在尝试创建一个 function,它将专门截取 tkinter window。

这是目前我发现的最好的方法:

    def save():
        pyautogui.keyDown('alt')
        pyautogui.keyDown('printscreen')
        pyautogui.keyUp('printscreen')
        pyautogui.keyUp('alt')
        self.img = ImageGrab.grabclipboard()
        self.img.save('paste.jpg', 'JPEG')

self.dataSend = Button(main, text = "Send", command = save).grid(column = 1, row = 13, sticky = W)

我使用pyautogui.keyDownUp进行alt + screenshot的原因是因为单击 function 打印屏幕仅应用程序 window。

但有时当我单击按钮Save时会出现错误:

    self.img.save('paste.jpg', 'JPEG')
AttributeError: 'NoneType' object has no attribute 'save'

还有其他选择吗? 并有一个更流畅的方式来截图 tkinter window 点击一个按钮并存储 jpg 文件?

您应该使用pyscreenshot

import pyscreenshot
pyscreenshot.grab().save('screenshot.png')

如果您需要获取屏幕的一部分,可以使用该选项:

im = pyscreenshot.grab(bbox=(10, 10, 510, 510))  # X1,Y1,X2,Y2
im.save('screenshot.png')

或者使用来自PillowImageGrab从剪贴板保存:

im = ImageGrab.grabclipboard()
im.save('screenshot.png')

它对我有用:

pyautogui.hotkey('alt', 'printscreen')
img = ImageGrab.grabclipboard()
img.save('screenshot.png')

注意抓取剪贴板仅适用于grabclipboard和 Mac OS

暂无
暂无

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

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