- #1
Eclair_de_XII
- 1,083
- 91
- TL;DR Summary
- Using PIL and win32gui in order to capture tkinter window as image, then save to file. It's always off-center, and I haven't a clue why.
Python:
from PIL import ImageGrab
from win32gui import GetWindowRect
def find_img_loc():
k=1
folder=sep.join((getcwd(),'screenshots'))
initial_file='screenshot'+str(k)
filename=lambda x: sep.join((folder,x+'.png'))
while exists(filename(initial_file)):
k+=1
n=len(str(k-1))
initial_file=initial_file[:-n]+str(k)
kw={
'initialfile':initial_file,\
'defaultextension':'png',\
'initialdir':folder,\
'filetypes':[('.png files only','*.png')]
}
filename=filedialog.asksaveasfilename(**kw)
return filename
def save_image(root):
if not exists('screenshots'):
mkdir('screenshots')
root.update()
HWND = root.winfo_id() # get the handle of the canvas
rect = GetWindowRect(HWND) # get the coordinate of the canvas
I am = ImageGrab.grab(rect) # get image of the current location
filename=find_img_loc()
if not filename:
return
else:
im.save(filename,format='png')
if __name__ == '__main__':
root=Tk()
lines='Sample text here','More sample text...','One more for the road.'
for n, text in enumerate(lines):
Label(root,text=text).grid(row=n)
save_image(root)
root.destroy()
This code was actually from:
https://stackoverflow.com/questions/9886274/how-can-i-convert-canvas-content-to-an-image
Last edited: