ui.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. """
  2. *REALLY* Small framework for creating/manipulating/deleting gui elements in Tkinter.
  3. NOTE: keep this synced with ui.js
  4. Author: Raphael Mannadiar
  5. Date: 2014/08/21
  6. """
  7. import Tkinter as tk
  8. from python_runtime.statecharts_core import Event
  9. from drawing import drawing
  10. from utils import utils
  11. class ui:
  12. window = None
  13. __nextWindowId = 0
  14. EVENTS = utils._bunch(
  15. KEY_PRESS = '<Key>',
  16. MOUSE_CLICK = '<Button>',
  17. MOUSE_MOVE = '<Motion>',
  18. MOUSE_PRESS = '<ButtonPress>',
  19. MOUSE_RELEASE = '<ButtonRelease>',
  20. MOUSE_RIGHT_CLICK = '<Button-3>',
  21. WINDOW_CLOSE = 'WM_DELETE_WINDOW');
  22. MOUSE_BUTTONS = utils._bunch(
  23. LEFT = 1,
  24. MIDDLE = 2,
  25. RIGHT = 3);
  26. KEYCODES = utils._bunch(
  27. DELETE = 46);
  28. @staticmethod
  29. def append_button(_window,text):
  30. button = tk.Button(_window, text=text)
  31. button.pack()
  32. return ui.wrap_element(button)
  33. @staticmethod
  34. def append_canvas(_window,width,height,style):
  35. canvas = tk.Canvas(_window,width=width,height=height)
  36. canvas.config(**style)
  37. canvas.pack()
  38. return drawing.canvas_wrapper(canvas)
  39. @staticmethod
  40. def bind_event(source,event,controller,raise_name,port="ui",time_offset=0.0):
  41. def __handle_event(ev=None):
  42. if event == ui.EVENTS.KEY_PRESS :
  43. controller.addInput(Event(raise_name, port, [ev.keycode,source]),time_offset)
  44. elif event == ui.EVENTS.MOUSE_CLICK or \
  45. event == ui.EVENTS.MOUSE_MOVE or \
  46. event == ui.EVENTS.MOUSE_PRESS or \
  47. event == ui.EVENTS.MOUSE_RELEASE or \
  48. event == ui.EVENTS.MOUSE_RIGHT_CLICK :
  49. controller.addInput(Event(raise_name, port, [ev.x, ev.y, ev.num]),time_offset)
  50. elif event == ui.EVENTS.WINDOW_CLOSE :
  51. controller.addInput(Event(raise_name, port, [source]),time_offset)
  52. else :
  53. raise Exception('Unsupported event');
  54. if event == ui.EVENTS.WINDOW_CLOSE :
  55. source.protocol(event, __handle_event)
  56. elif issubclass(drawing.ui_element_wrapper,source.__class__) :
  57. source.canvas_wrapper.element.tag_bind(source.element_id, event, __handle_event)
  58. else :
  59. source.bind(event, __handle_event)
  60. @staticmethod
  61. def close_window(_window):
  62. _window.destroy()
  63. @staticmethod
  64. def log(value):
  65. print(value)
  66. @staticmethod
  67. def new_window(width,height):
  68. _window = tk.Toplevel(ui.window)
  69. _window.geometry(str(width)+"x"+str(height)+"+300+300")
  70. return _window
  71. @staticmethod
  72. def println(value,target):
  73. raise Exception('Not implemented yet');
  74. @staticmethod
  75. def wrap_element(element):
  76. return utils._bunch(element=element)