2016-02-27 35 views
2

enter image description here使用Tkinter的绘制

我想弄清楚上面做蝙蝠图表最简单的方法具体条形图。我在学习tkinter,我知道我可以使用CanvasFrameLabel来做到这一点,但它似乎有太多冗余。

+1

你真的写了任何代码吗? – Ellis

回答

2

一些谷歌搜索显示this链接给我。

我已经包含了那里给出的示例代码,我希望能够对它进行评论,以便您能够理解发生了什么。

我稍微不确定我的for-loop描述的准确性,所以请评论是否有任何错误。

import tkinter as tk 


# Define the data points 
data = [20, 15, 10, 7, 5, 4, 3, 2, 1, 1, 0] 

root = tk.Tk() 
root.title("Bar Graph") 

c_width = 400 # Define it's width 
c_height = 350 # Define it's height 
c = tk.Canvas(root, width=c_width, height=c_height, bg='white') 
c.pack() 

# The variables below size the bar graph 
y_stretch = 15 # The highest y = max_data_value * y_stretch 
y_gap = 20 # The gap between lower canvas edge and x axis 
x_stretch = 10 # Stretch x wide enough to fit the variables 
x_width = 20 # The width of the x-axis 
x_gap = 20 # The gap between left canvas edge and y axis 

# A quick for loop to calculate the rectangle 
for x, y in enumerate(data): 

    # coordinates of each bar 

    # Bottom left coordinate 
    x0 = x * x_stretch + x * x_width + x_gap 

    # Top left coordinates 
    y0 = c_height - (y * y_stretch + y_gap) 

    # Bottom right coordinates 
    x1 = x * x_stretch + x * x_width + x_width + x_gap 

    # Top right coordinates 
    y1 = c_height - y_gap 

    # Draw the bar 
    c.create_rectangle(x0, y0, x1, y1, fill="red") 

    # Put the y value above the bar 
    c.create_text(x0 + 2, y0, anchor=tk.SW, text=str(y)) 

root.mainloop() 
1

最后这个简单的代码我写了,这可能是有点多余的,不是很灵活。

from tkinter import * 


root = Tk() 
root.title("Bar Graph") 

c_width = 500 
c_height = 200 
c = Canvas(root, width=c_width, height=c_height) 
c.pack() 

c.create_rectangle(20, 140, 120, 180, fill="red") 
c.create_text(70, 130, text="Projects--20%") 
c.create_rectangle(140, 160, 240, 180, fill="blue") 
c.create_text(190, 150, text="Quizzes--10%") 
c.create_rectangle(260, 120, 360, 180, fill="green") 
c.create_text(310, 110, text="Midterm--30%") 
c.create_rectangle(380, 100, 480, 180, fill="orange") 
c.create_text(430, 90, text="Final--40%") 
c.create_line(0, 180, 500, 180) 

root.mainloop()