Dlinet
Dlinet

Reputation: 1233

Working with the Python graphics module: is there any way to save the current window as an image?

I'm working with the python graphics module. What I am trying to do is save the current window as an image. In the module there is an option to save an "image" as an image (image.save()). But that isn't helpful because it just saves an image you have already loaded. OR if you load a blank image like I did in hopes drawing over it would change that, surprise, surprise: you get a blank image saved. Here is my code:

from graphics import *


w = 300
h = 300

anchorpoint=Point(150,150)
height=300
width=300

image=Image(anchorpoint, height, width) #creates a blank image in the background

win = GraphWin("Red Circle", w, h)
# circle needs center x, y coordinates and radius
center = Point(150, 150)
radius = 80
circle = Circle(center, radius)
circle.setFill('red')
circle.setWidth(2)
circle.draw(win)
point= circle.getCenter()

print point
pointx= point.getX()
pointy= point.getY()
print pointx
print pointy

findPixel=image.getPixel(150,150)
print findPixel
image.save("blank.gif")

# wait, click mouse to go on/exit
win.getMouse()
win.close()

#######that's it#####

so again here is my problem: How do I save what is now on the screen as "blank.gif" Thanks!

Upvotes: 2

Views: 6612

Answers (1)

Jean Jacques Gervais
Jean Jacques Gervais

Reputation: 36

The objects you are drawing are based on Tkinter. I don't believe you are actually drawing on the base image, but rather simply creating Tkinter objects by using the "graphics" library. I also don't believe you can save a Tkinter to a "gif" file, though you can definitely save them in postscript format, then covert them to a gif format.

In order to do this, you will need python's PIL library.

If all of your objects are actually TKinter objeccts, you can simply save the objects.

Start by replacing this line of code:

image.save("blank.gif")

With the following:

# saves the current TKinter object in postscript format
win.postscript(file="image.eps", colormode='color')

# Convert from eps format to gif format using PIL
from PIL import Image as NewImage
img = NewImage.open("image.eps")
img.save("blank.gif", "gif")

If you need additional information, please check out http://www.daniweb.com/software-development/python/code/216929 - which is where I got the suggested code.

I'm sure there are more elegant solutions available than save/convert, but since I don't know a lot about TKinter - this is the only way I've found.

Hope it helps!

Upvotes: 2

Related Questions