Python Turtle:单击时更改方形的pencolor

时间:2017-09-03 03:35:53

标签: python python-3.x turtle-graphics

我仍然是编程世界的新手,试图找到一些帮助。我不了解大部分代码。在我结束之前,我尝试了不同的方法:

import turtle
import random

window = turtle.Screen()
#window.colormode(255)

square = turtle.Turtle()
square.speed(0)
square.hideturtle()

square.up()
square.goto(-200, 200)
square.down()

for i in range(4):
    square.forward(50)
    square.right(90)

square.up()
square.goto(-205, 205)
square.write("Change Color")


pencil = turtle.Turtle()
pencil.shape("circle")

def drawing_controls(x, y):
    if (-200 <= x <= -150) and (150 <= y <= 200):
        pencil.color(random.random(), random.random(), random.random())

#def sqc (self, x, y):


window.onclick(drawing_controls)
#window.onclick(square.pencolor(random.random(), random.random(), 
random.random()))

pencil.onrelease(pencil.goto)

#comments的行是我之前尝试解决这个令人沮丧的问题之一。

1 个答案:

答案 0 :(得分:0)

我不确定你的实际目标,但我认为下面的返工会给你你正在寻找的行为。乌龟不是画一个正方形来点击,而是成为将被点击的正方形:

from turtle import Turtle, Screen
from random import random

def drawing_controls(x, y):
    pencil.color(random(), random(), random())
    square.color(*pencil.color())

def drag_pencil(x, y):
    pencil.ondrag(None)
    pencil.goto(x, y)
    pencil.ondrag(drag_pencil)

square = Turtle('square', visible=False)
square.speed('fastest')
square.hideturtle()
square.up()

square.goto(-200, 230)
square.write('Change Color', align='center')

square.goto(-200, 200)
square.shapesize(50 / 20)
square.showturtle()

pencil = Turtle('circle')

square.onclick(drawing_controls)

pencil.ondrag(drag_pencil)

window = Screen()
window.mainloop()

而不是onrelease(),我切换到ondrag()以使其更具互动性。但是,使用pencil.goto将无法顺利运行,尽管它是ondrag()处理程序的常见示例,因此我写了一个在拖动处理程序中禁用拖动事件的处理程序以平滑运动。