window.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. from tkinter import Toplevel, TclError
  2. import sys
  3. class WindowList:
  4. def __init__(self):
  5. self.dict = {}
  6. self.callbacks = []
  7. def add(self, window):
  8. window.after_idle(self.call_callbacks)
  9. self.dict[str(window)] = window
  10. def delete(self, window):
  11. try:
  12. del self.dict[str(window)]
  13. except KeyError:
  14. # Sometimes, destroy() is called twice
  15. pass
  16. self.call_callbacks()
  17. def add_windows_to_menu(self, menu):
  18. list = []
  19. for key in self.dict:
  20. window = self.dict[key]
  21. try:
  22. title = window.get_title()
  23. except TclError:
  24. continue
  25. list.append((title, key, window))
  26. list.sort()
  27. for title, key, window in list:
  28. menu.add_command(label=title, command=window.wakeup)
  29. def register_callback(self, callback):
  30. self.callbacks.append(callback)
  31. def unregister_callback(self, callback):
  32. try:
  33. self.callbacks.remove(callback)
  34. except ValueError:
  35. pass
  36. def call_callbacks(self):
  37. for callback in self.callbacks:
  38. try:
  39. callback()
  40. except:
  41. t, v, tb = sys.exc_info()
  42. print("warning: callback failed in WindowList", t, ":", v)
  43. registry = WindowList()
  44. add_windows_to_menu = registry.add_windows_to_menu
  45. register_callback = registry.register_callback
  46. unregister_callback = registry.unregister_callback
  47. class ListedToplevel(Toplevel):
  48. def __init__(self, master, **kw):
  49. Toplevel.__init__(self, master, kw)
  50. registry.add(self)
  51. self.focused_widget = self
  52. def destroy(self):
  53. registry.delete(self)
  54. Toplevel.destroy(self)
  55. # If this is Idle's last window then quit the mainloop
  56. # (Needed for clean exit on Windows 98)
  57. if not registry.dict:
  58. self.quit()
  59. def update_windowlist_registry(self, window):
  60. registry.call_callbacks()
  61. def get_title(self):
  62. # Subclass can override
  63. return self.wm_title()
  64. def wakeup(self):
  65. try:
  66. if self.wm_state() == "iconic":
  67. self.wm_withdraw()
  68. self.wm_deiconify()
  69. self.tkraise()
  70. self.focused_widget.focus_set()
  71. except TclError:
  72. # This can happen when the Window menu was torn off.
  73. # Simply ignore it.
  74. pass
  75. if __name__ == "__main__":
  76. from unittest import main
  77. main('idlelib.idle_test.test_window', verbosity=2)