如何解决绘制然后擦除正方形
我正在尝试使用 python 图形绘制一个正方形,然后在 3 秒后将其擦除。我有以下代码:
import threading as th
import turtle
import random
thread_count = 0
def draw_square():
turtle.goto(random.randint(-200,200),random.randint(-200,200))
for i in range(4):
turtle.forward(100)
turtle.left(90)
def erase_square(x,y):
turtle.pencolor('white')
turtle.fillcolor('white')
turtle.goto(x,y)
turtle.begin_fill()
for i in range(4):
turtle.forward(target_size)
turtle.left(90)
turtle.end_fill()
def square_timer():
global thread_count
if thread_count <= 10:
print("Thread count",thread_count)
draw_square()
T = th.Timer(3,square_timer)
T.start()
square_update() 函数将绘制 10 个正方形然后停止。我试图让它绘制一个正方形,然后使用擦除正方形()通过在其上绘制白色来清除它,然后另一个并重复该过程并在达到 10 时停止。我不知道如何使擦除功能转到绘制正方形的随机位置并“擦除”它。我怎样才能让它绘制和擦除正方形?
解决方法
清除绘图最直接的方法是使用 clear()
方法,而不是尝试在图像上绘制白色:
from turtle import Screen,Turtle
from random import randint
def draw_square():
turtle.goto(randint(-200,200),randint(-200,200))
turtle.pendown()
for _ in range(4):
turtle.forward(100)
turtle.left(90)
turtle.penup()
def erase_square():
turtle.clear()
screen.ontimer(square_update) # no time,ASAP
def square_update():
draw_square()
screen.ontimer(erase_square,3000) # 3 seconds in milliseconds
screen = Screen()
turtle = Turtle()
turtle.hideturtle()
turtle.speed('fastest')
turtle.penup()
square_update()
screen.exitonclick()
您可以按照@JonathanDrukker 的建议使用 undo()
方法,但您必须撤消每一步。即使对于像正方形这样简单的形状,这也需要一点思考,但是对于复杂的形状,这很困难。添加到撤消缓冲区的操作数并不总是与您对乌龟的调用相匹配。但是我们可以从海龟本身获得这个计数,只要我们在绘制和擦除之间不做任何其他海龟动作:
def draw_square():
turtle.goto(randint(-200,200))
count = turtle.undobufferentries()
turtle.pendown()
for _ in range(4):
turtle.forward(100)
turtle.left(90)
turtle.penup()
return turtle.undobufferentries() - count
def erase_square(undo_count):
for _ in range(undo_count):
turtle.undo()
screen.ontimer(square_update)
def square_update():
undo_count = draw_square()
screen.ontimer(lambda: erase_square(undo_count),3000)
但我要做的是让海龟本身成为正方形,然后移动它而不是擦除并(重新)绘制正方形:
from turtle import Screen,Turtle
from random import randint
CURSOR_SIZE = 20
def draw_square():
turtle.goto(randint(-200,200))
def square_update():
turtle.hideturtle()
draw_square()
turtle.showturtle()
screen.ontimer(square_update,3000)
screen = Screen()
turtle = Turtle()
turtle.hideturtle()
turtle.shape('square')
turtle.shapesize(100 / CURSOR_SIZE)
turtle.fillcolor('white')
turtle.penup()
square_update()
screen.exitonclick()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。