ObservableIntVar


   1 '''
   2 Here is an example of a new IntVar widget that uses an observer pattern
   3 to control program flow.  Note that this sets a variable that broadcasts
   4 to all relevant "listeners" that's its value has been changed.  The
   5 variable's value is set by the widget but could be set by anything else
   6 as well.  For example, if you have some other process that changes the
   7 observable it could notify the widget to update to the new value as
   8 well. - Brian Kelley
   9 '''
  10 
  11 from Tkinter import *
  12 import Dialog
  13 
  14 class Observable:
  15      def __init__(self, data):
  16          self.data = None
  17          self.callbacks = []
  18 
  19      def addCallback(self, func):
  20          """(function)-> add listeners"""
  21          self.callbacks.append(func)
  22 
  23      def set(self, data):
  24          """(data)->set the variable to be equal to data and
  25          call all listeners"""
  26          self.data = data
  27          for callback in self.callbacks:
  28              callback(data)
  29 
  30 class ObservableIntVar(Frame):
  31      def __init__(self, master, **kw):
  32          apply(Frame.__init__, (self, master), kw)
  33          self._var = IntVar()
  34          b = Checkbutton(master,
  35                          variable=self._var,
  36                          command=self._setVar)
  37          b.pack()
  38          self._observable = Observable(self._var.get())
  39 
  40      def _setVar(self):
  41          self._observable.set(self._var.get())
  42          Dialog.Dialog(self,
  43                        title="Hello",
  44                        text="I'm set to %s"%self._var.get(),
  45                        bitmap=Dialog.DIALOG_ICON,
  46                        default=0, strings=('OK',))
  47 
  48      def add(self, callback):
  49          """(callback)->add a callback function that should be
  50          notified when the value of the IntVar changes"""
  51          self._observable.addCallback(callback)
  52 
  53 if __name__ == "__main__":
  54      tk = Tk()
  55      ob = ObservableIntVar(tk)
  56      ob.pack()
  57 
  58      def callback(data):
  59          print "callback called with data =", data
  60 
  61      ob.add(callback)
  62 
  63      mainloop() 
  64 

tkinter: ObservableIntVar (last edited 2011-12-07 21:22:06 by AnthonyMuss)