我正在使用 tkinter 和turtle 在 python 中制作一个类似绘画的应用程序。我正在尝试将绘制的图像保存为 png。
我的程序的简短版本:
import tkinter as tk
from functools import partial
from turtle import TurtleScreen, RawTurtle, Shape
from PIL import Image
def draw(x, y):
turtle.ondrag(None)
turtle.pendown()
turtle.goto(x, y)
turtle.penup()
screen.update()
turtle.ondrag(draw)
def move(x, y):
screen.onclick(None)
turtle.goto(x, y)
screen.onclick(move)
screen.update()
def set_color(color):
global pen_color
pen_color = color
turtle.pencolor(color)
screen.update()
# --- add widgets ---
root = tk.Tk()
canvas = tk.Canvas(root, width=500, height=500)
canvas.pack(side='right', expand=True, fill='both')
frame = tk.Frame(root)
frame.pack(side='left', fill='y')
tk.Label(frame, text='COLORS').grid(column=0, row=0)
tk.Button(frame, bg='red', width=10, command=partial(set_color, 'red')).grid(column=0, row=1)
tk.Button(frame, bg='yellow', width=10, command=partial(set_color, 'yellow')).grid(column=0, row=2)
tk.Button(frame, bg='green', width=10, command=partial(set_color, 'green')).grid(column=0, row=3)
tk.Button(frame, bg='blue', width=10, command=partial(set_color, 'blue')).grid(column=0, row=4)
tk.Button(frame, bg='black', width=10, command=partial(set_color, 'black')).grid(column=0, row=5)
def save () :
drawing = screen.getcanvas()
drawing.postscript(file='drawing.ps')
img = Image.open( 'drawing.ps')
img.save('drawing.png')
print('...dumping gui window to png')
bsave = tk.Button(
frame,
text='save *',
width=10,
command=save
)
bsave.grid(column=0, row=6)
screen = TurtleScreen(canvas)
screen.tracer(False)
pen_color = 'black'
turtle = RawTurtle(screen)
#turtle.hideturtle()
turtle.shape("circle")
polygon = turtle.get_shapepoly()
fixed_color_turtle = Shape("compound")
fixed_color_turtle.addcomponent(polygon, "", "")
screen.register_shape('fixed', fixed_color_turtle)
turtle.shape("fixed")
turtle.penup()
turtle.pensize(5)
turtle.turtlesize(2000,2000)
turtle.ondrag(draw)
screen.onscreenclick(move)
screen.update()
screen.mainloop()
当我运行此命令时,我收到错误:OSError:无法在路径上找到 Ghostscript
我想尝试一些没有 Ghostscript 的东西(这是一个学校项目,也需要在大学计算机上运行,而且他们上面没有 GhostScript 的东西),但我看到的大多数解决方案都涉及它。
我也尝试过这个,但返回的 x 和 y 值总是错误的
def save () :
x0 = frame.winfo_rootx()
y0 = frame.winfo_rooty()
x1 = x0 + frame.winfo_width()
y1 = y0 + frame.winfo_height()
ImageGrab.grab().crop((x0, y0, x1, y1)).save('painting.png')
你可以使用这样的东西:
from tkinter import *
import turtle
turtle.forward(100)
screen = turtle.getscreen()
screen.getcanvas().postscript(file="FILE_NAME.eps")
将其保存为 eps 文件,您可以在线查看或谷歌如何将其转换为 png。