How to do a screenshot of a tkinter application?
I need to do a screenshot of the content of the tkinter application below. I am on Windows 7 (or 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()
Since you mentioned that you are on Windows. You can use the Win32 API
as directed in this answer Fastest way to take a screenshot with python on windows. Hope this helps.
But actually Pyscreenshot should be what you are looking for.
Take the following code for example:
from pyscreenshot import grab
im = grab(bbox=(100, 200, 300, 400))
im.show()
As you can see you can use bbox
to take screenshot that is at co-ordinates (100, 200) and has a width of 300 and a height of 400.
Also as regards the printing check out Printing using win32api. I hope these help.
Using PIL you can do a resize:
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)
I would advise changing your program so that you can resize the image before printing
I made a module that takes screenshot of tkinter window.
You can install with: pip install tkcap
GitHub repository
Usage:
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