graph.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import tkinter as tk
  2. import time, math
  3. from PIL import Image, ImageDraw, ImageTk
  4. class Graph(tk.Canvas):
  5. def __init__(self, root, **kwargs):
  6. self.root = root
  7. tk.Canvas.__init__(self, root, **kwargs)
  8. self.height = self.winfo_reqheight()
  9. self.width = self.winfo_reqwidth()
  10. self.coord = [(10, 50), (20, 50), (100, 100)]
  11. self.drawBackground()
  12. self.canvas = self.bg.copy()
  13. self.image = self.create_image(0, 0, image=None, anchor='nw')
  14. self.bind("<Configure>", self.on_resize)
  15. self.scale = 450 / 2
  16. def drawBackground(self):
  17. self.bg = Image.new('RGB', (self.width, self.height), (0,20,0))
  18. draw = ImageDraw.Draw(self.bg)
  19. draw.line([(0, self.height/2), (self.width, self.height/2)], (0,127,127), 1)
  20. draw.line([(self.width/2, 0), (self.width/2, self.height)], (0,127,127), 1)
  21. def on_resize(self,event):
  22. # determine the ratio of old width/height to new width/height
  23. self.width = max(400, event.width-4)
  24. self.height = max(400, event.height-4)
  25. # resize the canvas
  26. self.config(width=self.width, height=self.height)
  27. self.canvas = self.canvas.resize((self.width, self.height))
  28. self.drawBackground()
  29. self.canvas = Image.blend(self.canvas, self.bg, 0.1)
  30. def update(self, data):
  31. self.coord = [self.coord[-1]]
  32. for point in data[0]:
  33. self.coord.append((point[0] / self.scale * self.width/2, point[1] / self.scale * self.height/2))
  34. self.canvas = Image.blend(self.canvas, self.bg, 1/250)
  35. draw = ImageDraw.Draw(self.canvas)
  36. draw.line(self.coord, fill=(100, 255, 100, 255), width=int(self.height/100), joint='curve')
  37. self.photo = ImageTk.PhotoImage(self.canvas)
  38. self.itemconfig(self.image, image=self.photo)