window.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import sys
  2. import numpy as np
  3. # Only ask users to install matplotlib if they actually need it
  4. try:
  5. import matplotlib.pyplot as plt
  6. except:
  7. print('To display the environment in a window, please install matplotlib, eg:')
  8. print('pip3 install --user matplotlib')
  9. sys.exit(-1)
  10. class Window:
  11. """
  12. Window to draw a gridworld instance using Matplotlib
  13. """
  14. def __init__(self, title):
  15. self.fig = None
  16. self.imshow_obj = None
  17. # Create the figure and axes
  18. self.fig, self.ax = plt.subplots()
  19. # Show the env name in the window title
  20. self.fig.canvas.set_window_title(title)
  21. # Turn off x/y axis numbering/ticks
  22. self.ax.set_xticks([], [])
  23. self.ax.set_yticks([], [])
  24. # Flag indicating the window was closed
  25. self.closed = False
  26. def close_handler(evt):
  27. self.closed = True
  28. self.fig.canvas.mpl_connect('close_event', close_handler)
  29. def show_img(self, img):
  30. """
  31. Show an image or update the image being shown
  32. """
  33. # Show the first image of the environment
  34. if self.imshow_obj is None:
  35. self.imshow_obj = self.ax.imshow(img, interpolation='bilinear')
  36. self.imshow_obj.set_data(img)
  37. self.fig.canvas.draw()
  38. # Let matplotlib process UI events
  39. # This is needed for interactive mode to work properly
  40. plt.pause(0.001)
  41. def set_caption(self, text):
  42. """
  43. Set/update the caption text below the image
  44. """
  45. plt.xlabel(text)
  46. def reg_key_handler(self, key_handler):
  47. """
  48. Register a keyboard event handler
  49. """
  50. # Keyboard handler
  51. self.fig.canvas.mpl_connect('key_press_event', key_handler)
  52. def show(self, block=True):
  53. """
  54. Show the window, and start an event loop
  55. """
  56. # If not blocking, trigger interactive mode
  57. if not block:
  58. plt.ion()
  59. # Show the plot
  60. # In non-interative mode, this enters the matplotlib event loop
  61. # In interactive mode, this call does not block
  62. plt.show()
  63. def close(self):
  64. """
  65. Close the window
  66. """
  67. plt.close()