from Tkinter import *
root = Tk()
cv = Canvas(root)
cv.create_rectangle(10,10,50,50)
cv.pack()
root.mainloop()
我想将画布内容转换为位图或其他图像,然后执行其他操作,例如旋转或缩放图像,或更改其坐标。
如果我不再画画,位图可以提高效率。
我该怎么办?
答案 0 :(得分:21)
你可以生成一个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()
答案 1 :(得分:15)
我找到了一个很好的方法,这真的很有帮助。为此,您需要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)处)你的屏幕)。
ImageGrab.grab()
制作了一个版画屏幕,然后我将其裁剪为仅包含小部件的位。虽然不完美,并且不会制作出最佳图像,但这是一个很好的工具,可以获取任何小部件的图像并保存它。
如果您有任何疑问,请发表评论!希望这有帮助!
答案 2 :(得分:0)
也许您可以尝试使用widget_winfo_id获取画布的HWND。
import win32gui
from PIL import ImageGrab
HWND = canvas.winfo_id() # get the handle of the canvas
rect = win32gui.GetWindowRect(HWND) # get the coordinate of the canvas
im = ImageGrab.grab(rect) # get image of the current location
答案 3 :(得分:-1)
使用枕头将Postscript转换为PNG
select act_dprt_dtmz, CAST(act_dprt_dtmz as timestamp) - cast(from_unixtime(unix_timestamp('act_dprt_dtmz')+840) as timestamp) from heart_beat_data_temp;