window.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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.imshow_obj is None:
  35. self.imshow_obj = self.ax.imshow(img, interpolation="bilinear")
  36. # Update the image data
  37. self.imshow_obj.set_data(img)
  38. # Request the window be redrawn
  39. self.fig.canvas.draw_idle()
  40. self.fig.canvas.flush_events()
  41. # Let matplotlib process UI events
  42. plt.pause(0.001)
  43. def set_caption(self, text):
  44. """
  45. Set/update the caption text below the image
  46. """
  47. plt.xlabel(text)
  48. def reg_key_handler(self, key_handler):
  49. """
  50. Register a keyboard event handler
  51. """
  52. # Keyboard handler
  53. self.fig.canvas.mpl_connect("key_press_event", key_handler)
  54. def show(self, block=True):
  55. """
  56. Show the window, and start an event loop
  57. """
  58. # If not blocking, trigger interactive mode
  59. if not block:
  60. plt.ion()
  61. # Show the plot
  62. # In non-interative mode, this enters the matplotlib event loop
  63. # In interactive mode, this call does not block
  64. plt.show()
  65. def close(self):
  66. """
  67. Close the window
  68. """
  69. plt.close()
  70. self.closed = True