鱼C论坛

 找回密码
 立即注册
查看: 2028|回复: 1

在保留两个for循环的条件下,怎么让柱状图正常画出

[复制链接]
发表于 2023-12-10 19:05:02 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
import turtle


# Function that draws the turtle
def drawBar(t, height, color):
    # Get turtle t to draw one bar
    # of height

    # Start filling this shape
    t.fillcolor(color)
    t.begin_fill()
    t.left(90)
    t.forward(height)
    t.write(str(height))
    t.right(90)
    t.forward(40)
    t.right(90)
    t.forward(height)
    t.left(90)

    # stop filling the shape
    t.end_fill()

# Driver Code
s_list=[423, 117,1235, 96, 134,789, 354]
for i in range(7):
    count = s_list[i]
    xs = [count]
    clrs = ["green", "red", "yellow", "black",
            "pink", "brown", "blue"]

    maxheight = max(xs)
    numbers = len(xs)
    border = 100

# Set up the window and its
# attributes
    wn = turtle.Screen()
    wn.setworldcoordinates(0 - border, 0 - border,
                           40 * numbers + border,
                           maxheight + border)

    tess = turtle.Turtle()
    tess.pensize(3)

    for x in range(len(xs)):
        drawBar(tess, xs[x],
                clrs[x])
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2023-12-10 19:05:20 | 显示全部楼层
在你的代码中,绘制柱状图的部分有一些问题。首先,你应该使用循环变量 `i` 来获取每个元素的高度和颜色,而不是直接使用列表本身。另外,在绘制每个柱状图时,你应该使用索引 `x` 来获取对应的高度和颜色。

以下是修改后的代码:
  1. import turtle
  2. # Function that draws the turtle
  3. def drawBar(t, height, color):
  4.     # Get turtle t to draw one bar
  5.     # of height
  6.     # Start filling this shape
  7.     t.fillcolor(color)
  8.     t.begin_fill()
  9.     t.left(90)
  10.     t.forward(height)
  11.     t.write(str(height))
  12.     t.right(90)
  13.     t.forward(40)
  14.     t.right(90)
  15.     t.forward(height)
  16.     t.left(90)
  17.     # stop filling the shape
  18.     t.end_fill()
  19. # Driver Code
  20. s_list = [10, 30, 20, 40, 50, 15, 25]
  21. clrs = ["red", "green", "blue", "yellow", "orange", "purple", "pink"]
  22. maxheight = max(s_list)
  23. numbers = len(s_list)
  24. border = 100
  25. # Set up the window and its attributes
  26. wn = turtle.Screen()
  27. wn.setworldcoordinates(0 - border, 0 - border,
  28.                        40 * numbers + border,
  29.                        maxheight + border)
  30. tess = turtle.Turtle()
  31. tess.pensize(3)
  32. for x in range(len(s_list)):
  33.     drawBar(tess, s_list[x], clrs[x])
  34.    
  35. turtle.done()
复制代码

希望这可以解决你的问题!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-24 04:16

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表