window.py 2.4 KB

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