【问题标题】:Python Turtle: change pencolor of square when clickingPython Turtle:单击时更改正方形的笔颜色
【发布时间】:2018-02-11 16:30:12
【问题描述】:

我还是编程界的新手,正在努力寻求帮助。我看不懂大部分代码。在我来到这里之前,我已经尝试了不同的方法:

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)

带有# cmets 的行来自我之前为解决这个令人沮丧的问题所做的众多尝试之一。

【问题讨论】:

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


    【解决方案1】:

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

    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() 以使其更具交互性。然而,尽管ondrag() 处理程序是一个常见示例,但使用pencil.goto 不会顺利进行,因此我编写了一个处理程序,在拖动处理程序中禁用拖动事件以平滑运动。

    【讨论】:

    • 这绝对是我要找的,我把正方形变成了一个可以点击的正方形,而不是用乌龟画它!但我仍然无法解决着色部分。非常感谢!!
    猜你喜欢
    • 2015-08-11
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    相关资源
    最近更新 更多