使用Python图形模块:如何将当前窗口保存为图像?

2 投票
1 回答
6485 浏览
提问于 2025-04-17 08:29

我正在使用Python的graphics模块。我想做的是把当前窗口保存为一张图片。在这个模块里,有一个选项可以用来保存“图像”(image.save())。但这并没有什么帮助,因为它只是保存你已经加载的图像。或者,如果你像我一样加载一张空白的图像,希望在上面绘画后能改变它,结果却是:你保存的还是一张空白的图像。以下是我的代码:

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#####

所以我的问题是:我该如何把现在屏幕上显示的内容保存为“blank.gif”?谢谢!

1 个回答

2

你正在绘制的对象是基于Tkinter的。我觉得你并不是在真正的基础图像上绘图,而是通过使用“图形”库简单地创建Tkinter对象。我也认为你不能直接把Tkinter保存为“gif”文件,不过你可以先保存为后记格式(postscript),然后再转换成gif格式。

为了做到这一点,你需要使用Python的PIL库。

如果你所有的对象实际上都是Tkinter对象,你可以直接保存这些对象。

首先,把这行代码替换为:

image.save("blank.gif")

用下面的代码:

# 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")

如果你需要更多的信息,可以查看这个链接:http://www.daniweb.com/software-development/python/code/216929 - 这是我找到的建议代码的来源。

我相信还有比保存/转换更优雅的解决方案,但因为我对Tkinter了解不多,所以这是我找到的唯一方法。

希望这对你有帮助!

撰写回答