Advertisement
here2share

# Tk_bar_graph.py

Jan 10th, 2019
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.24 KB | None | 0 0
  1. # Tk_bar_graph.py
  2.  
  3. from Tkinter import *
  4. from random import *
  5.  
  6. # Define the data points
  7. data = [20, 15, 10, 7, 5, 4, 3, 2, 1, 1, 0]
  8.  
  9. root = Tk()
  10. root.title("Bar Graph")
  11.  
  12. c_width = 400  # Define it's width
  13. c_height = 350  # Define it's height
  14. canvas = Canvas(root, width=c_width, height=c_height, bg='white')
  15. canvas.pack()
  16.  
  17. # The variables below size the bar graph
  18. y_stretch = 15  # The highest y = max_data_value * y_stretch
  19. y_gap = 20  # The gap between lower canvas edge and x axis
  20. x_stretch = 10  # Stretch x wide enough to fit the variables
  21. x_width = 20  # The width of the x-axis
  22. x_gap = 20  # The gap between left canvas edge and y axis
  23.  
  24. # A quick for loop to calculate the rectangle
  25. for x, y in enumerate(data):
  26.  
  27.     # coordinates of each bar
  28.  
  29.     # Bottom left coordinate
  30.     x0 = x * x_stretch + x * x_width + x_gap
  31.  
  32.     # Top left coordinates
  33.     y0 = c_height - (y * y_stretch + y_gap)
  34.  
  35.     # Bottom right coordinates
  36.     x1 = x * x_stretch + x * x_width + x_width + x_gap
  37.  
  38.     # Top right coordinates
  39.     y1 = c_height - y_gap
  40.  
  41.     # Draw the bar
  42.     canvas.create_rectangle(x0, y0, x1, y1, fill="red")
  43.  
  44.     # Put the y value above the bar
  45.     canvas.create_text(x0 + 2, y0, anchor=SW, text=str(y))
  46.  
  47. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement