【问题标题】:Python making turtle graphic by using list colorsPython使用列表颜色制作海龟图形
【发布时间】:2018-12-07 01:04:54
【问题描述】:

每次单击时,我都会尝试制作具有更改颜色的正方形。但是当我运行它时,它只会填充红色。如何每次都改变颜色?

import turtle
t= turtle.Turtle()
s=turtle.Screen()
colors = ["red","orange","yellow","green","blue","indigo","purple"]
n=0

def square(x,y):
    t.penup()
    t.goto(x,y)
    t.pendown()
    t.color(colors[n])
    t.begin_fill()   
    for i in range(4):
        t.fd(90)
        t.lt(90)
    t.end_fill()
    t.penup()
if s.onscreenclick(square) == True:
    n+=1

【问题讨论】:

  • 至少复制代码文本,这样我们就不必重新输入了:)
  • 我打印了代码请帮助
  • 尝试在if语句中更改t.color(),而不是使用全局变量n

标签: python list turtle-graphics


【解决方案1】:

您错过了对s.mainloop() 的呼叫。如果您希望 n 在每次单击时更改,请在 square() 函数中将其声明为全局,并在完成绘制后将其递增。如果n 大于len(colors),请不要忘记将其重置为零。

s.onscreenclick() 的调用告诉海龟“如何处理点击”(在这种情况下通过调用square()),因此您不需要放入if 语句。

import turtle
t= turtle.Turtle()
s=turtle.Screen()
colors = ["red","orange","yellow","green","blue","indigo","purple"]
n=0

def square(x,y): # draw a square at (x,y)
    global n # use the global variable n
    t.penup()
    t.goto(x,y)
    t.pendown()
    t.color(colors[n])
    t.begin_fill()
    for i in range(4):
        t.fd(90)
        t.lt(90)
    t.end_fill()
    t.penup()
    n = (n+1) % len(colors) # change the colour after each square

s.onscreenclick(square) # whenever there's a click, call square()

s.mainloop() # start looping

最后,请务必read this,因为这是您第一次使用 *。

【讨论】:

    【解决方案2】:

    我更喜欢使用来自 itertools 的cycle(),而不是全局计数器和模数运算,它只是不断重复列表:

    from turtle import Turtle, Screen
    from itertools import cycle
    
    colors = cycle(["red", "orange", "yellow", "green", "blue", "indigo", "purple"])
    
    def square(x, y):
        screen.onscreenclick(None)  # disable handler inside handler
    
        turtle.penup()
        turtle.goto(x, y)
        turtle.pendown()
    
        turtle.color(next(colors))
    
        turtle.begin_fill()
        for _ in range(4):
            turtle.forward(75)
            turtle.left(90)
        turtle.end_fill()
    
        turtle.penup()
    
        screen.onscreenclick(square)
    
    screen = Screen()
    turtle = Turtle()
    
    screen.onscreenclick(square)
    
    screen.mainloop()
    

    还请注意,我在处理程序的实现中禁用了 onscreenclick() 处理程序,因此用户无法在前一个正方形仍在绘制时单击,因为这会导致结果混乱。

    【讨论】: