如何做一个tkinter应用程序的屏幕截图?

时间:2013-11-13 21:07:26

标签: python tkinter ttk

我需要在下面对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()

2 个答案:

答案 0 :(得分:2)

由于您提到您在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)

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

答案 1 :(得分:1)

我制作了一个可以截取 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
相关问题