2012-03-27 148 views
12
from Tkinter import * 
root = Tk() 
cv = Canvas(root) 
cv.create_rectangle(10,10,50,50) 
cv.pack() 
root.mainloop() 

我想将画布内容转换为位图或其他图像,然后执行其他操作,例如旋转或缩放图像或更改其坐标。如何将画布内容转换为图像?

位图可以提高效率,以显示我是否不再绘图。

我应该怎么办?

+0

在actionscript中它有draw()函数来实现,如何在python tkinter中工作? – liupeixin 2012-03-28 01:57:58

回答

14

您可以生成一个postscript文件(喂到一些其他的工具:ImageMagick的,Ghostscript的,等等):

from Tkinter import * 
root = Tk() 
cv = Canvas(root) 
cv.create_rectangle(10,10,50,50) 
cv.pack() 
root.mainloop() 

cv.update() 
cv.postscript(file="file_name.ps", colormode='color') 

root.mainloop() 

或并联借鉴PIL和Tkinter的画布上相同的图像(见:Saving a Tkinter Canvas Drawing (Python) )。例如(在同一篇文章的启发):

from Tkinter import * 
import Image, ImageDraw 

width = 400 
height = 300 
center = height//2 
white = (255, 255, 255) 
green = (0,128,0) 

root = Tk() 

# Tkinter create a canvas to draw on 
cv = Canvas(root, width=width, height=height, bg='white') 
cv.pack() 

# PIL create an empty image and draw object to draw on 
# memory only, not visible 
image1 = Image.new("RGB", (width, height), white) 
draw = ImageDraw.Draw(image1) 

# do the Tkinter canvas drawings (visible) 
cv.create_line([0, center, width, center], fill='green') 

# do the PIL image/draw (in memory) drawings 
draw.line([0, center, width, center], green) 

# PIL image can be saved as .png .jpg .gif or .bmp file (among others) 
filename = "my_drawing.jpg" 
image1.save(filename) 

root.mainloop() 
9

我发现这样做是真正有用的好方法。为此,您需要PIL模块。这里是代码:

from PIL import ImageGrab 

def getter(widget): 
    x=root.winfo_rootx()+widget.winfo_x() 
    y=root.winfo_rooty()+widget.winfo_y() 
    x1=x+widget.winfo_width() 
    y1=y+widget.winfo_height() 
    ImageGrab.grab().crop((x,y,x1,y1)).save("file path here") 

这是做什么的,你传递一个小部件名称到函数中。命令root.winfo_rootx()root.winfo_rooty()获得整个root窗口左上角的像素位置。

然后,将widget.winfo_x()widget.winfo_y()添加到,基本上只是获取要捕获的小部件的左上角像素的像素坐标(在屏幕的像素(x,y)处)。

然后,我找到(x1,y1),它是窗口小部件的左下角像素。 ImageGrab.grab()制作一个打印屏幕,然后我裁剪它只获取包含小部件的位。虽然不是完美的,并且不会制作出最好的图像,但这是用于获取任何小部件的图像并保存它的好工具。

如果您有任何疑问,请发表评论!希望这有助于!

+0

嗨,当我运行代码时,它使得图片过早。你可以请示例脚本tkinter图形,然后保存它?也许我在错误的时间放置或调用了该功能。 – 2017-01-30 16:57:14

+0

@EerikMuuli当您想要拍摄照片时,您只能调用该功能。例如,你可以得到一个带有命令的按钮,并且在按钮命令的函数中,只需放置'getter(x)',其中x是窗口小部件,甚至是整个根窗口。这应该没有问题。如果您还有其他问题,请在此处回复评论。 – 2017-01-31 20:11:22

+0

好的,我发现问题出在哪里 - 我会在这里粘贴我的代码。脚本现在所做的是它将两次打印画布并发生错误 - 尽管它应该打开一次并在4.5秒后关闭它。它还打印出2次“wut”,这真的很奇怪。这是代码:http://pastebin.com/MPgABMEv – 2017-02-01 19:14:27