Convert images drawn by turtle to PNG in Python

不羁的心 提交于 2019-12-01 02:18:15

问题


I'm making a abstract art template generator in Python that takes inputs of minimum radius, maximum radius, and number of circles. It draws random circles in random places, also meeting the user's specifications. I want to convert the Turtle graphics into a PNG so that the user can then edit the template however he/she wants to, but I don't know how to proceed. Here's my code:

import random  
import time  
import turtle  

print("Abstract Art Template Generator")
print()
print("This program will generate randomly placed and sized circles on a blank screen.")
num = int(input("Please specify how many circles you would like to be drawn: "))
radiusMin = int(input("Please specify the minimum radius you would like to have: "))
radiusMax = int(input("Please specify the maximum radius you would like to have: "))
screenholder = input("Press ENTER when you are ready to see your circles drawn: ")

t = turtle.Pen()

win = turtle.Screen()


def mycircle():
    x = random.randint(radiusMin,radiusMax) 
    t.circle(x)

    t.up()
    y = random.randint(0,360)
    t.seth(y)
    if t.xcor() < -300 or t.xcor() > 300:
        t.goto(0, 0)
    elif t.ycor() < -300 or t.ycor() > 300:
        t.goto(0, 0)
    z = random.randint(0,100)
    t.forward(z)
    t.down()


for i in range(0, num):
    mycircle()


turtle.done()

回答1:


Converting from a postscript file (*.ps) to a PNG can be done with ghostscript. This open-source program is available on multiple platforms. Another option is ImageMagick, also open source and multi platform.

Just search on the internet for "convert ps to PNG ghostscript" or "convert ps to PNG Imagemagick".

If you want to automate the conversion, have a look at the subprocess module (python documentation) to call the program from within your python program.




回答2:


You can use turtle.getcanvas() to generate Tkinker canvas. Then save it as postscript file.

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

turtle.done()

Then you can convert it to png (I think you will find how to do it). Or use PIL with Tkinker - more about this method here



来源:https://stackoverflow.com/questions/35629520/convert-images-drawn-by-turtle-to-png-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!