0001 from Tkinter import * 0002 0003 0004 class WidgetRedirector: 0005 0006 """Support for redirecting arbitrary widget subcommands.""" 0007 0008 def __init__(self, widget): 0009 self.dict = {} 0010 self.widget = widget 0011 self.tk = tk = widget.tk 0012 w = widget._w 0013 self.orig = w + "_orig" 0014 tk.call("rename", w, self.orig) 0015 tk.createcommand(w, self.dispatch) 0016 0017 def __repr__(self): 0018 return "WidgetRedirector(%s<%s>)" % (self.widget.__class__.__name__, 0019 self.widget._w) 0020 0021 def close(self): 0022 for name in self.dict.keys(): 0023 self.unregister(name) 0024 widget = self.widget; del self.widget 0025 orig = self.orig; del self.orig 0026 tk = widget.tk 0027 w = widget._w 0028 tk.deletecommand(w) 0029 tk.call("rename", orig, w) 0030 0031 def register(self, name, function): 0032 if self.dict.has_key(name): 0033 previous = dict[name] 0034 else: 0035 previous = OriginalCommand(self, name) 0036 self.dict[name] = function 0037 setattr(self.widget, name, function) 0038 return previous 0039 0040 def unregister(self, name): 0041 if self.dict.has_key(name): 0042 function = self.dict[name] 0043 del self.dict[name] 0044 if hasattr(self.widget, name): 0045 delattr(self.widget, name) 0046 return function 0047 else: 0048 return None 0049 0050 def dispatch(self, cmd, *args): 0051 m = self.dict.get(cmd) 0052 try: 0053 if m: 0054 return m(*args) 0055 else: 0056 return self.tk.call((self.orig, cmd) + args) 0057 except TclError: 0058 return "" 0059 0060 0061 class OriginalCommand: 0062 0063 def __init__(self, redir, name): 0064 self.redir = redir 0065 self.name = name 0066 self.tk = redir.tk 0067 self.orig = redir.orig 0068 self.tk_call = self.tk.call 0069 self.orig_and_name = (self.orig, self.name) 0070 0071 def __repr__(self): 0072 return "OriginalCommand(%r, %r)" % (self.redir, self.name) 0073 0074 def __call__(self, *args): 0075 return self.tk_call(self.orig_and_name + args) 0076 0077 0078 def main(): 0079 root = Tk() 0080 text = Text() 0081 text.pack() 0082 text.focus_set() 0083 redir = WidgetRedirector(text) 0084 global orig_insert 0085 def my_insert(*args): 0086 print "insert", args 0087 orig_insert(*args) 0088 orig_insert = redir.register("insert", my_insert) 0089 root.mainloop() 0090 0091 if __name__ == "__main__": 0092 main() 0093
Generated by PyXR 0.9.4