0

I am trying to trace a variable:

    def callback(*args):
        print "variable changed!"
    self.entryVariable = Tkinter.StringVar()
    self.entryVariable.trace("w", callback)

This works fine, but I want to actually print out the variable in callback:

    def callback(self.entryVariable):
        print "variable changed!"
        print self.entryVariable.get()
    self.entryVariable = Tkinter.StringVar()
    self.entryVariable.trace("w", callback(self.entryVariable))

But, I get

def callback(self.entryVariable):
                 ^
SyntaxError: invalid syntax 
Sam Weisenthal
  • 2,791
  • 9
  • 28
  • 66

1 Answers1

2

You've made the classic mistake of not giving the trace() function a function object, but the return value of that function. You could use lambda, but you don't have to use any parameter at all, so just use

self.entryVariable.trace("w", self.callback)

You can mention any self.xxx attribute anywhere in your class, so your method becomes:

def callback(self, *args):
    print "variable changed!"
    print self.entryVariable.get()
TidB
  • 1,749
  • 1
  • 12
  • 14
  • Not *anywhere*. As long as `callback` is defined inside of a class instance method, then `self` should be available. – OozeMeister Mar 21 '15 at 13:59
  • Suppose I wanted to define callback outside of the method with the `self.entryVariable.trace("w", self.callback)`? I would like to bind changes in the variable to an event.. – Sam Weisenthal Mar 21 '15 at 14:01
  • By the way, `def callback(*args):`seems to work, but `def callback():` gives `return self.func(*args) TypeError: callback() takes no arguments (3 given)` – Sam Weisenthal Mar 21 '15 at 14:02
  • 1
    @user99889 fix'd. And I've already assumed your defining the method outside the other method, as your calling your methods like `self.callback`. – TidB Mar 21 '15 at 14:04