【问题标题】:Turtle colour doesn't change with variable and list乌龟颜色不随变量和列表而变化
【发布时间】:2019-11-20 11:12:08
【问题描述】:

所以这是我现在的代码,问题应该在第 18 行和第 37 行之间。我想要做的是,当用户单击左上角的海龟时,它会变为下一种颜色。左上角的乌龟只是光学的,除了告诉用户点击哪里之外没有其他功能(至少是这样的想法)。问题是它没有这样做,我真的不明白为什么

import turtle
from turtle import *

# def on_click_handler(x,y):
# print("Clicked: " , [x,y])
# t1.goto(x,y)

sc = Screen()
sc.setup(400, 400, 10, 10)
sc.setworldcoordinates(-300, -300, 300, 300)
# sc.onscreenclick(on_click_handler)

t1 = Turtle("turtle")
t1.shape("circle")
t1.shapesize(0.25, 0.25)
t1.speed(-1)

#changing turtle colour
tcolour = Turtle("turtle")
tcolour.penup()
tcolour.shape("square")
tcolour.shapesize(1, 1.5)
tcolour.setpos(-275, 285)
colour_list = ["#000000", "#0101DF", "#04B404", "#FF0000", "#FF8000", "B40486"] #black, blue, green, red, orange, purple
n = 0

def colourchange(x, y):
    if (x < -275 and x > -300 and y > 284 and y < 300):
        global n
        n += 1


turtle.onscreenclick(colourchange, 1)
turtle.listen()

t1.color(colour_list[0+n])

def dragging(x, y):
    t1.ondrag(None)
    t1.setheading(t1.towards(x, y))
    t1.goto(x, y)
    t1.ondrag(dragging)


def clickright(x, y):
    t1.clear()


def main():
    turtle.listen()

    t1.ondrag(dragging)
    turtle.onscreenclick(clickright, 3)

    sc.mainloop()


main()

而且我不认为我被允许导入 tkinter,至少我认为我们的教授是这么说的

【问题讨论】:

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


    【解决方案1】:

    每当你以两种不同的方式导入同一个模块时,你就已经陷入了困境:

    import turtle
    from turtle import *
    

    您在区分海龟和屏幕时遇到了问题——使用上述方法可以解决这些问题。我建议你只使用turtle的面向对象接口并关闭功能接口:

    from turtle import Screen, Turtle
    

    您尝试将海龟用作按钮,这很好,但是您将点击处理程序放在屏幕上,并在您单击海龟时让处理程序测试。相反,将点击处理程序放在海龟上,这样你就不需要测试了。 (同样,不清楚乌龟做什么以及屏幕做什么的问题的一部分。)

    虽然你调用了两次,listen() 在这里并不适用,因为它还没有处理键盘输入。

    最后,您的颜色更改处理程序更新了颜色索引,但实际上从未更改任何颜色。以下是我为解决上述问题而对您的代码进行的返工和简化:

    from turtle import Screen, Turtle
    
    COLOUR_LIST = ['black', 'blue', 'green', 'red', 'orange', 'purple']
    
    colour_index = 0
    
    def colour_change(x, y):
        global colour_index
    
        colour_index = (colour_index + 1) % len(COLOUR_LIST)
        t1.color(COLOUR_LIST[colour_index])
    
    def dragging(x, y):
        t1.ondrag(None)
        t1.setheading(t1.towards(x, y))
        t1.goto(x, y)
        t1.ondrag(dragging)
    
    def click_right(x, y):
        t1.clear()
    
    t1 = Turtle('circle')
    t1.shapesize(0.5)
    t1.speed('fastest')
    t1.color(COLOUR_LIST[colour_index])
    t1.ondrag(dragging)
    
    # changing colour turtle
    tcolour = Turtle('square')
    tcolour.penup()
    tcolour.shapesize(1, 1.5)
    tcolour.setpos(-275, 285)
    tcolour.onclick(colour_change, 1)
    
    screen = Screen()
    screen.onclick(click_right, btn=3)
    screen.mainloop()
    

    【讨论】:

    • 非常感谢您的帮助,更感谢您的解释。现在更有意义了
    猜你喜欢
    • 2019-09-17
    • 2020-08-11
    • 2018-05-24
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    相关资源
    最近更新 更多