我在我的程序中实现了以下保存功能,它允许用户将他/她用 Turtle 在 Tkinter 画布上绘制的任何内容保存为 JPEG 文件。它的工作原理是首先捕获屏幕和 Tkinter 画布,然后基于它创建一个 postscript 文件。然后它将该 postscript 文件转换为 PIL(Python 成像库)可读文件类型,然后 PIL 将转换后的文件保存为 JPEG。我的保存功能如下所示:
def savefirst():
# Capture screen and Tkinter canvas
cnv = getscreen().getcanvas()
global hen
# Save screen and canvas as Postscript file
ps = cnv.postscript(colormode = 'color')
# Open a Tkinter file dialog that allows to input his.her own name for the file
hen = filedialog.asksaveasfilename(defaultextension = '.jpg')
# Convert Postscript file to PIL readable format
im = Image.open(io.BytesIO(ps.encode('utf-8')))
# Finally save converted …Run Code Online (Sandbox Code Playgroud) 取向:
我创建了以下函数以允许用户将乌龟更改为他/她选择的图像,然后在任何时候将其标记到画布:
def TurtleShape():
try:
# Tkinter buttons related to turtle manipulation
manipulateimage.config(state = NORMAL)
flipButton.config(state = NORMAL)
mirrorButton.config(state = NORMAL)
originalButton.config(state = NORMAL)
resetturtle.config(state = NORMAL)
rotateButton.config(state = NORMAL)
# Ask user for file name from tkinter file dialog, and return file name as `klob`
global klob
klob = filedialog.askopenfilename()
global im
# Open `klob` and return as `im`
im = Image.open(klob)
# Append `im` to pictures deque
pictures.append(im)
# Clear `edited` deque
edited.clear()
# Save `im` as an …Run Code Online (Sandbox Code Playgroud) python image-manipulation turtle-graphics python-3.x python-3.5
所以我在我的程序中创建了一个函数,允许用户将他/她在Turtle画布上绘制的任何内容保存为带有他/她自己名字的Postscript文件.但是,根据Postscript文件的性质,输出中没有出现某些颜色的问题,而且Postscript文件也不会在其他平台上打开.因此我决定将postscript文件保存为JPEG图像,因为JPEG文件应该能够在许多平台上打开,希望能够显示画布的所有颜色,并且它应该具有比postscript文件更高的分辨率.所以,为此,我尝试使用PIL,在我的保存功能中使用以下内容:
def savefirst():
cnv = getscreen().getcanvas()
global hen
fev = cnv.postscript(file = 'InitialFile.ps', colormode = 'color')
hen = filedialog.asksaveasfilename(defaultextension = '.jpg')
im = Image.open(fev)
print(im)
im.save(hen + '.jpg')
Run Code Online (Sandbox Code Playgroud)
但是,每当我运行它时,我都会收到此错误:
line 2391, in savefirst
im = Image.open(fev)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PIL/Image.py", line 2263, in open
fp = io.BytesIO(fp.read())
AttributeError: 'str' object has no attribute 'read'
Run Code Online (Sandbox Code Playgroud)
显然它不能读取postscript文件,因为据我所知,它本身不是一个图像,因此必须先将其转换为图像,然后将其作为图像读取,最后转换并保存为JPEG文件.问题是,我怎样才能首先将postscript文件转换为可能使用Python Imaging Library的程序中的图像文件?环顾SO和谷歌一直没有帮助,所以SO用户的任何帮助都非常感谢!
编辑:按照unubuntu's建议,我现在有这个为我的保存功能:
def savefirst():
cnv = getscreen().getcanvas()
global hen
ps = cnv.postscript(colormode = 'color')
hen …Run Code Online (Sandbox Code Playgroud)