graph.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. # determine the ratio of old width/height to new width/height
  24. self.width = max(400, event.width-4)
  25. self.height = max(400, event.height-4)
  26. # resize the canvas
  27. self.config(width=self.width, height=self.height)
  28. self.canvas = self.canvas.resize((self.width, self.height))
  29. self.drawBackground()
  30. self.canvas = Image.blend(self.canvas, self.bg, 0.1)
  31. def pointToCoord(self, point):
  32. return ((point[0] - self.scale[0]) / (self.scale[1]-self.scale[0]) * self.width,
  33. self.height - (point[1] - self.scale[0]) / (self.scale[1]-self.scale[0]) * self.height - 1)
  34. def update(self, data):
  35. coord = [[self.pointToCoord(p)] for p in self.lastPoints]
  36. for i in range(len(data)):
  37. for point in data[i]:
  38. coord[i].append(self.pointToCoord(point))
  39. self.lastPoints = [line[-1] for line in data]
  40. self.canvas = Image.blend(self.canvas, self.bg, 1/200)
  41. draw = ImageDraw.Draw(self.canvas)
  42. for i in range(len(coord)):
  43. draw.line(coord[i], fill=self.colors[i], width=int(self.height/100), joint='curve')
  44. self.photo = ImageTk.PhotoImage(self.canvas)
  45. self.itemconfig(self.image, image=self.photo)