我正在设置两个定义,我希望fillColor从drawBar中读取。程序没有读取与值对应的正确颜色。
import turtle
wn = turtle.Screen() # Set up the window
wn.bgcolor("white")
tess = turtle.Turtle()
tess.penup()
tess.goto(-100,-75)
tess.pendown()
def drawBar(t, height):
""" Get turtle t to draw one bar, of height. """
t.left(90)
t.begin_fill()# Point up
t.forward(height)
# Draw up the left side
t.right(90)
t.forward(40) # width of bar, along the top
t.right(90)
t.forward(height)
t.end_fill()# And down again!
t.left(90)
def drawColor(t, height):
drawBar(t, height)
if height >= 200:
return tess.fillcolor("red")
elif height < 200 and v >= 100:
return tess.fillcolor("yellow")
elif height < 100:
return tess.fillcolor("green")
xs = [48, 117, 200, 240, 160, 260, 220]
for v in xs: # assume xs and tess are ready
drawColor(tess, v)
我不知道为什么这不起作用。
答案 0 :(得分:0)
我想你在引用height
测试时可能会输入错字:
elif height < 200 and v >= 100:
return tess.fillcolor("yellow")
应该是:
elif 100 <= height < 200:
return tess.fillcolor("yellow")
v
可能在全球范围内找到,而不是您想要测试的内容。
此外,您正在传递对龟对象的引用,但您没有使用它:
def drawColor(t, height):
drawBar(t, height)
if height >= 200:
# return tess.fillcolor("red")
return t.fillcolor("red")
...
答案 1 :(得分:0)
将drawColor
更改为:
def drawColor(t, height):
if height >= 200:
t.fillcolor("red")
elif height < 200 and height >= 100:
t.fillcolor("yellow")
elif height < 100:
t.fillcolor("green")
drawBar(t, height)
这样,您首先要根据当前高度设置正确的颜色,然后绘制条形图。在原始代码中,您使用当前颜色(从默认颜色黑色开始)绘制一个条形图,然后更改要绘制的颜色,因此每个新条形图都以最后一个颜色应该具有的颜色绘制。
在原始代码中也存在其他一些问题。您不使用传递的乌龟对象t
,而是使用全局的tess
。也无需返回fillcolor
来电的结果。