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