将乌龟图形保存到.eps文件时,背景颜色显示在屏幕上,但不会保存在.eps文件中

Ret*_*ing 5 python tkinter eps

我是Python的新手,并且一直在使用海龟模块作为学习语言的一种方式.

感谢stackoverflow,我研究并学习了如何将图像复制到封装的postscript文件中,并且效果很好.然而,有一个问题.该turtle模块允许在屏幕上显示但不显示在.eps文件中的背景颜色.所有其他颜色,即笔颜色和乌龟颜色,使其通过,但不是背景颜色.

感兴趣的是,我不相信导入Tkinter是必要的,因为我不相信我在Tkinter这里使用任何模块.我将其作为尝试诊断问题的一部分.我也用过bgcolor=Orange而不是用s.bgcolor="orange".

没有喜悦.

我包括一个简单的代码示例:

# Python 2.7.3 on a Mac

import turtle
from Tkinter import *

s=turtle.Screen()
s.bgcolor("orange")

bob = turtle.Turtle()
bob.circle(250)

ts=bob.getscreen()
ts.getcanvas().postscript(file = "turtle.eps")
Run Code Online (Sandbox Code Playgroud)

我试图发布屏幕和.eps文件的图像,但stackoverflow将不允许我作为新用户这样做.某种垃圾邮件预防.虽然简单到可视化,但屏幕背景颜色为橙色,eps文件为白色.

从.eps文件生成的输出

我很感激任何想法.

mar*_*eau 3

Postscript 设计用于在纸张或胶片等介质上制作标记,而不是光栅图形。因此,它本身没有可以设置为给定颜色的背景颜色,因为这通常是所使用的纸张或未曝光胶片的颜色。

为了模拟这一点,您需要绘制一个画布大小的矩形,并用您想要的背景颜色填充它。我在海龟模块中没有看到任何内容来查询返回的画布对象getcanvas(),我能想到的唯一替代方法是读取turtle.cfg文件(如果有),或者只是硬编码默认的300x400大小。您也许可以查看源代码并找出当前画布尺寸的存储位置并直接访问它们。

更新:

我只是在 Python 控制台中使用该turtle模块,发现画布返回的内容有一个getcanvas()名为. 该对象具有似乎包含当前海龟图形窗口尺寸的方法。所以我会尝试绘制一个该大小的填充矩形,看看是否能满足您的需求。_canvas<Tkinter.Canvas instance>winfo_width()winfo_height()

更新2:

下面的代码显示了如何执行我的建议。注意:必须在绘制任何其他图形之前绘制背景,否则创建的实心填充背景矩形将覆盖屏幕上的所有其他内容。

此外,添加的draw_background()功能还努力保存并稍后将图形状态恢复到原来的状态。根据您的具体使用情况,这可能不是必需的。

import turtle


def draw_background(a_turtle):
    """ Draw a background rectangle. """
    ts = a_turtle.getscreen()
    canvas = ts.getcanvas()
    height = ts.getcanvas()._canvas.winfo_height()
    width = ts.getcanvas()._canvas.winfo_width()

    turtleheading = a_turtle.heading()
    turtlespeed = a_turtle.speed()
    penposn = a_turtle.position()
    penstate = a_turtle.pen()

    a_turtle.penup()
    a_turtle.speed(0)  # fastest
    a_turtle.goto(-width/2-2, -height/2+3)
    a_turtle.fillcolor(turtle.Screen().bgcolor())
    a_turtle.begin_fill()
    a_turtle.setheading(0)
    a_turtle.forward(width)
    a_turtle.setheading(90)
    a_turtle.forward(height)
    a_turtle.setheading(180)
    a_turtle.forward(width)
    a_turtle.setheading(270)
    a_turtle.forward(height)
    a_turtle.end_fill()

    a_turtle.penup()
    a_turtle.setposition(*penposn)
    a_turtle.pen(penstate)
    a_turtle.setheading(turtleheading)
    a_turtle.speed(turtlespeed)

s = turtle.Screen()
s.bgcolor("orange")

bob = turtle.Turtle()
draw_background(bob)

ts = bob.getscreen()
canvas = ts.getcanvas()

bob.circle(250)

canvas.postscript(file="turtle.eps")

s.exitonclick()  # optional
Run Code Online (Sandbox Code Playgroud)

这是实际生成的输出(通过 Photoshop 在屏幕上渲染):

EPS 文件的输出