簡體   English   中英

Python 中的 Turtle 模塊:

[英]Turtle module in Python:

這里的問題是:編寫一個名為 barChart 的非結果函數,它將數據的數字列表作為參數,並繪制條形圖。 編寫一個完整的程序來調用這個函數。 不幸的是,當前版本的 drawBar 函數通過標簽底部繪制了條形圖的頂部。 一個很好的闡述是使標簽完全顯示在頂線上方。 為了保持間距一致,您可能會向 drawBar 傳遞一個額外的參數,以便向上移動距離。 對於 barChart 函數,將該參數設為 maxheight+border 的一小部分。 填充操作使此修改特別棘手:您將希望移過欄的頂部並在繪制和填充欄之前或之后寫入。

我應該改變什么?

這是我的代碼:

import turtle

def drawBar(t, height):
""" Get turtle t to draw one bar, of height. """
t.begin_fill()               # start filling this shape
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)
t.end_fill()                 # stop filling this shape

您可以傳遞數字列表的最大值,然后分別繪制文本和條形圖。

試試這個代碼:

import turtle

def drawBar(t, height, mx):
    # draw text
    t.penup()
    t.left(90)
    t.forward(mx*10+10)
    t.write(str(height).center(12))
    t.right(180)
    t.forward(mx*10+10)
    t.left(90)
    t.pendown()
    
    """ Get turtle t to draw one bar, of height. """
    t.fillcolor(.1, 1-1*height/mx/2, .1)  # darker is higher value
    t.begin_fill()       # start filling this shape
    t.left(90)
    t.forward(height*10)
    #t.write("  " + str(height))
    t.right(90)
    t.forward(40)
    t.right(90)
    t.forward(height*10)
    t.left(90)
    t.end_fill() 
    
    # bottom line
    t.right(180)
    t.forward(40)
    t.right(180)
    t.forward(40)
    
t = turtle.Turtle()

nums = [3,1,4,1,5,9,2]

t.speed(0) # fastest
for n in nums:
   drawBar(t, n, max(nums))
t.hideturtle()

input('Enter to exit')

輸出

圖表

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM