graph.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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, scale=(-100, 500), **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.lastPoints = [(0, 0)] * 3
  11. self.scale = scale
  12. self.colors = [(100, 255, 100, 255), (255, 100, 100, 255) ,(100, 100, 255, 255)]
  13. self.drawBackground()
  14. self.canvas = self.bg.copy()
  15. self.image = self.create_image(0, 0, image=None, anchor='nw')
  16. self.bind("<Configure>", self.on_resize)
  17. def drawBackground(self):
  18. self.bg = Image.new('RGB', (self.width, self.height), (0,20,0))
  19. draw = ImageDraw.Draw(self.bg)
  20. draw.line([(0, self.height/2), (self.width, self.height/2)], (0,127,127), 1)
  21. draw.line([(self.width/2, 0), (self.width/2, self.height)], (0,127,127), 1)
  22. def on_resize(self,event):
  23. self.width = max(100, event.width-4)
  24. self.height = max(100, event.height-4)
  25. # resize the canvas
  26. self.canvas = self.canvas.resize((self.width, self.height))
  27. self.drawBackground()
  28. self.canvas = Image.blend(self.canvas, self.bg, 0.1)
  29. def pointToCoord(self, point):
  30. return ((point[0] - self.scale[0]) / (self.scale[1]-self.scale[0]) * self.width,
  31. self.height - (point[1] - self.scale[0]) / (self.scale[1]-self.scale[0]) * self.height - 1)
  32. def update(self, data):
  33. coord = [[self.pointToCoord(p)] for p in self.lastPoints]
  34. for i in range(len(data)):
  35. for point in data[i]:
  36. coord[i].append(self.pointToCoord(point))
  37. self.lastPoints = [line[-1] for line in data]
  38. self.canvas = Image.blend(self.canvas, self.bg, 1/200)
  39. draw = ImageDraw.Draw(self.canvas)
  40. for i in range(len(coord)):
  41. draw.line(coord[i], fill=self.colors[i], width=int(self.height/100), joint='curve')
  42. self.photo = ImageTk.PhotoImage(self.canvas)
  43. self.itemconfig(self.image, image=self.photo)