SearchDialog.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. from Tkinter import *
  2. from idlelib import SearchEngine
  3. from idlelib.SearchDialogBase import SearchDialogBase
  4. def _setup(text):
  5. root = text._root()
  6. engine = SearchEngine.get(root)
  7. if not hasattr(engine, "_searchdialog"):
  8. engine._searchdialog = SearchDialog(root, engine)
  9. return engine._searchdialog
  10. def find(text):
  11. pat = text.get("sel.first", "sel.last")
  12. return _setup(text).open(text,pat)
  13. def find_again(text):
  14. return _setup(text).find_again(text)
  15. def find_selection(text):
  16. return _setup(text).find_selection(text)
  17. class SearchDialog(SearchDialogBase):
  18. def create_widgets(self):
  19. SearchDialogBase.create_widgets(self)
  20. self.make_button("Find Next", self.default_command, 1)
  21. def default_command(self, event=None):
  22. if not self.engine.getprog():
  23. return
  24. self.find_again(self.text)
  25. def find_again(self, text):
  26. if not self.engine.getpat():
  27. self.open(text)
  28. return False
  29. if not self.engine.getprog():
  30. return False
  31. res = self.engine.search_text(text)
  32. if res:
  33. line, m = res
  34. i, j = m.span()
  35. first = "%d.%d" % (line, i)
  36. last = "%d.%d" % (line, j)
  37. try:
  38. selfirst = text.index("sel.first")
  39. sellast = text.index("sel.last")
  40. if selfirst == first and sellast == last:
  41. text.bell()
  42. return False
  43. except TclError:
  44. pass
  45. text.tag_remove("sel", "1.0", "end")
  46. text.tag_add("sel", first, last)
  47. text.mark_set("insert", self.engine.isback() and first or last)
  48. text.see("insert")
  49. return True
  50. else:
  51. text.bell()
  52. return False
  53. def find_selection(self, text):
  54. pat = text.get("sel.first", "sel.last")
  55. if pat:
  56. self.engine.setcookedpat(pat)
  57. return self.find_again(text)
  58. def _search_dialog(parent):
  59. root = Tk()
  60. root.title("Test SearchDialog")
  61. width, height, x, y = list(map(int, re.split('[x+]', parent.geometry())))
  62. root.geometry("+%d+%d"%(x, y + 150))
  63. text = Text(root)
  64. text.pack()
  65. text.insert("insert","This is a sample string.\n"*10)
  66. def show_find():
  67. text.tag_add(SEL, "1.0", END)
  68. s = _setup(text)
  69. s.open(text)
  70. text.tag_remove(SEL, "1.0", END)
  71. button = Button(root, text="Search", command=show_find)
  72. button.pack()
  73. if __name__ == '__main__':
  74. from idlelib.idle_test.htest import run
  75. run(_search_dialog)