【问题标题】:How to do a screenshot of a tkinter application?如何截取 tkinter 应用程序的屏幕截图?
【发布时间】:2013-11-26 16:16:07
【问题描述】:

我需要对下面的 tkinter 应用程序的内容进行截图。我在 Windows 7(或 8)上。

from Tkinter import *

def test(x):    
    #print "I'm in event:", x
    if x == 1:            # if event on entry e1 
        print 'e1 event' # do some thing
    elif x == 2:            # also if event on entry e2    
        print 'e2 event'  # do some thing else
    else: 
        print 'no event' 

def test1(x):
    test(1)

def test2(x):
    test(2)


root=Tk()
root.minsize(500,500)
e1=Entry(root)
e1.pack()

e2=Entry(root)
e2.pack()

e1.bind( "<FocusOut>", test1) 
e2.bind( "<FocusOut>", test2)   
button=Button(root, text='print').pack(side=BOTTOM)

root.mainloop()

【问题讨论】:

  • 我假设你想要一些代码来做到这一点?如果没有,您可以使用 Windows 应用程序中内置的Snipping Tools。否则我会看看我能做什么

标签: python tkinter ttk


【解决方案1】:

既然你提到你在 Windows 上。您可以按照此答案Fastest way to take a screenshot with python on windows 中的指示使用Win32 API。希望这会有所帮助。


但实际上Pyscreenshot 应该是您要查找的内容。

以如下代码为例:

from pyscreenshot import grab

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

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

同样关于打印检查Printing using win32api。我希望这些帮助。

使用 PIL 可以调整大小:

from PIL import Image
from pyscreenshot import grab

img = grab(bbox=(100, 200, 300, 400))

# to keep the aspect ratio
w = 300
h = 400
maxheight = 600
maxwidth = 800
ratio = min(maxwidth/width, maxheight/height)
# correct image size is not #oldsize * ratio#

# img.resize(...) returns a resized image and does not effect img unless
# you assign the return value
img = img.resize((h * ratio, width * ratio), Image.ANTIALIAS)

我建议您更改程序,以便在打印前调整图像大小

【讨论】:

  • 我使用 win32api 打印,但打印的图像看起来放大了太多,不适合所有内容!!!!
  • 那么在'Printing using win32api'代码中操作哪个参数以使打印比例适合图像内容?
  • 把它留在我身边,我会看看我能做什么
  • 我删除了这两行 bmp.size[1]: bmp = bmp.rotate (90) ##>>> 并进行了缩放- 高度固定在 6500,非常完美......
【解决方案2】:

我制作了一个对 tkinter 窗口进行截图的模块。

您可以安装:pip install tkcap

GitHub repository

用法:

import tkcap

cap = tkcap.CAP(master)     # master is an instance of tkinter.Tk
cap.capture(FileName)       # Capture and Save the screenshot of the tkiner window

【讨论】:

  • 只是指出这是特定于 Windows 的。 (这也是 OP 的内容 - 只需添加此评论以让其他 Linux 用户在安装之前知道)。
猜你喜欢
  • 1970-01-01
  • 2011-03-18
  • 1970-01-01
  • 2021-08-27
  • 2011-05-08
  • 1970-01-01
  • 1970-01-01
  • 2013-11-17
  • 1970-01-01
相关资源
最近更新 更多