Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

python - 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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...