You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python Turtle Graphics保存图片时,如何隐藏绘图光标?

解决Python Turtle导出图片时乌龟光标无法隐藏的问题

问题描述

使用Python Turtle绘制图形后,通过turtle.getscreen().getcanvas().postscript()导出EPS图片时,即便调用hideturtle()方法,乌龟光标仍会显示在导出的图片中。尝试过删除光标、重置画布、将光标移到屏幕外等方法,均无法解决问题——调用getscreen()后光标会回到屏幕中心。

示例代码:

import turtle
t = turtle.Turtle()

t.fillcolor("red")
t.begin_fill()

t.circle(100)

t.end_fill()
t.getscreen().getcanvas().postscript(file="output.eps")

解决方案

方法1:隐藏光标后强制刷新屏幕

在导出图片前,先隐藏乌龟光标,再调用turtle.update()强制刷新屏幕,确保光标状态生效:

import turtle
t = turtle.Turtle()

t.fillcolor("red")
t.begin_fill()
t.circle(100)
t.end_fill()

# 隐藏光标并刷新屏幕
t.hideturtle()
turtle.update()

t.getscreen().getcanvas().postscript(file="output.eps")

方法2:创建乌龟时直接设置为不可见

初始化乌龟对象时,通过visible=False参数让光标从一开始就不显示,避免后续的显示问题:

import turtle
# 创建时直接隐藏光标
t = turtle.Turtle(visible=False)

t.fillcolor("red")
t.begin_fill()
t.circle(100)
t.end_fill()

t.getscreen().getcanvas().postscript(file="output.eps")

方法3:使用屏幕对象控制显示

获取屏幕对象后,先关闭自动刷新,绘制完成后隐藏光标再手动刷新:

import turtle
t = turtle.Turtle()
screen = turtle.getscreen()
screen.tracer(0)  # 关闭自动刷新

t.fillcolor("red")
t.begin_fill()
t.circle(100)
t.end_fill()

t.hideturtle()
screen.update()  # 手动刷新屏幕

screen.getcanvas().postscript(file="output.eps")

内容的提问来源于stack exchange,提问作者Laszlo Pav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 01:52:10