window.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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.xaxis.set_ticks_position('none')
  23. self.ax.yaxis.set_ticks_position('none')
  24. _ = self.ax.set_xticklabels([])
  25. _ = self.ax.set_yticklabels([])
  26. # Flag indicating the window was closed
  27. self.closed = False
  28. def close_handler(evt):
  29. self.closed = True
  30. self.fig.canvas.mpl_connect('close_event', close_handler)
  31. def show_img(self, img):
  32. """
  33. Show an image or update the image being shown
  34. """
  35. # If no image has been shown yet,
  36. # show the first image of the environment
  37. if self.imshow_obj is None:
  38. self.imshow_obj = self.ax.imshow(img, interpolation='bilinear')
  39. # Update the image data
  40. self.imshow_obj.set_data(img)
  41. # Request the window be redrawn
  42. self.fig.canvas.draw_idle()
  43. self.fig.canvas.flush_events()
  44. # Let matplotlib process UI events
  45. plt.pause(0.001)
  46. def set_caption(self, text):
  47. """
  48. Set/update the caption text below the image
  49. """
  50. plt.xlabel(text)
  51. def reg_key_handler(self, key_handler):
  52. """
  53. Register a keyboard event handler
  54. """
  55. # Keyboard handler
  56. self.fig.canvas.mpl_connect('key_press_event', key_handler)
  57. def show(self, block=True):
  58. """
  59. Show the window, and start an event loop
  60. """
  61. # If not blocking, trigger interactive mode
  62. if not block:
  63. plt.ion()
  64. # Show the plot
  65. # In non-interative mode, this enters the matplotlib event loop
  66. # In interactive mode, this call does not block
  67. plt.show()
  68. def close(self):
  69. """
  70. Close the window
  71. """
  72. plt.close()
  73. self.closed = True