使用resetscreen()的turtle程序中的概念性错误

2024-04-20 03:45:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我要达到的标准: 当用户按下空格键时,屏幕将重置,这意味着绘制的线将消失,未命名的海龟将返回中心,但它不会返回默认的海龟颜色和形状!

""" A simple drawing program

Click and drag the center turtle to draw
Click the colorful buttons to change the
turtle's color,
and then draw different shapes.
Press the SPACEBAR key to reset the
drawing.
"""

from turtle import *

turtle_1 = Turtle()
turtle_2 = Turtle()
turtle_3 = Turtle()

def callback_1(x,y):
    color("red")
    shape("circle")
    circle(100)

def callback_2(x,y):
    color("blue")
    shape("square")
    circle(100,steps=4)

def callback_3(x,y):
    color("green")
    shape("triangle")
    circle(100,steps=3)

def place_turtles():
    turtle_1.color("red")
    turtle_1.shape("circle")
    turtle_1.penup()
    turtle_1.goto(-200,-200)
    turtle_2.color("blue")
    turtle_2.shape("square")
    turtle_2.penup()
    turtle_2.goto(0,-200)
    turtle_3.color("green")
    turtle_3.shape("triangle")
    turtle_3.penup()
    turtle_3.goto(200,-200)

def start_over():
    resetscreen()
    place_turtles()

listen()
onkey(start_over, "space")

ondrag(goto)

place_turtles()

此代码允许用户拖动海龟,按下按钮,并在按下空格键时重置屏幕。不过,由于某种原因,重置屏幕也会重置海龟的颜色。我怎样才能防止这种情况发生?你知道吗

基本上我想发生的是,如果,比方说,用户点击蓝色正方形按钮,然后重置屏幕以隐藏按钮绘制的形状,所有的海龟返回到他们原来的位置,但未命名的海龟不改变它以前的颜色和形状。如果我需要进一步说明,请告诉我。你知道吗


Tags: theto用户屏幕颜色defcolor重置
1条回答
网友
1楼 · 发布于 2024-04-20 03:45:02

抱着“迟到总比不到好”的态度,我相信我已经修改了你的代码,以达到你想要的行为。我还修改了拖动逻辑,以提高绘图能力:

from turtle import Turtle, Screen, getturtle

def callback_1(x, y):
    anonymous.color(*turtle_1.color())
    anonymous.shape(turtle_1.shape())
    anonymous.circle(100)

def callback_2(x, y):
    anonymous.color(*turtle_2.color())
    anonymous.shape(turtle_2.shape())
    anonymous.circle(100, steps=4)

def callback_3(x, y):
    anonymous.color(*turtle_3.color())
    anonymous.shape(turtle_3.shape())
    anonymous.circle(100, steps=3)

def setup_turtles():
    turtle_1.onclick(callback_1)
    turtle_1.color("red")
    turtle_1.penup()
    turtle_1.goto(-200, -200)

    turtle_2.onclick(callback_2)
    turtle_2.color("blue")
    turtle_2.penup()
    turtle_2.goto(0, -200)

    turtle_3.onclick(callback_3)
    turtle_3.color("green")
    turtle_3.penup()
    turtle_3.goto(200, -200)

def start_over():
    colors = anonymous.color()
    anonymous.reset()
    anonymous.color(*colors)

def drag_handler(x, y):
    anonymous.ondrag(None)  # disable event inside event handler
    anonymous.goto(x, y)
    anonymous.ondrag(drag_handler)  # reenable event on event handler exit

anonymous = getturtle()
anonymous.ondrag(drag_handler)

turtle_1 = Turtle(shape="circle")
turtle_2 = Turtle(shape="square")
turtle_3 = Turtle(shape="triangle")

setup_turtles()

screen = Screen()
screen.onkey(start_over, "space")
screen.listen()

screen.mainloop()

许多变化只是出于个人风格的原因。两个关键更改是:只需重置匿名海龟本身,而不是屏幕;而不是使用goto作为事件处理程序,而是将其包装在一个函数中,该函数在goto调用期间关闭拖动事件。你知道吗

相关问题 更多 >