我试图用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个正方形,然后停止。我试图让它画一个正方形,然后用erase_square()在它上面涂上白色,然后再重复这个过程,当它达到10时停止。我不知道如何使擦除函数转到绘制的方块的随机位置,并‘擦除’它。我怎样才能让它画和擦除正方形?
发布于 2021-04-21 16:47:59
清除绘图最简单的方法是使用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()
方法,但是您必须撤销每个步骤。即使是像正方形这样简单的形状,这需要一点思考,但对于一个复杂的形状,这是困难的。添加到undo缓冲区的操作数并不总是与您对turtle的调用相匹配。但是我们可以从海龟身上得到这个计数,只要我们在画和擦除之间不做任何其他的海龟动作:
def draw_square():
turtle.goto(randint(-200, 200), 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), 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()
https://stackoverflow.com/questions/67176779
复制相似问题