Using the same function more than once whilst passing arguments in Tk is not as simple as it seems. Many people --including myself-- start with something like this.
- Code: Select all
#This code ommiits many formalities.
Button(frame,command=self.foo(x)).grid()
def foo(y):
print "I like " + str(y)
- Code: Select all
#This code ommits many formalities.
Button(frame,command=lambda: self.foo(x)).grid()
def foo(y):
print "I like " + str(y)
Thread Revisited: Entire months have gone by since i posted this, and now i feel very n00bish.
- Code: Select all
# Formalities omitted
def foo(x): return x + 10
my_button = tk.Button(parent_widget, command=foo(10))
- Code: Select all
my_button = tk.Button(parent_widget, command=20)
To remedy this, we utilize lambda. From my understanding, lambda can be simply put as a "function not bound to a name"; importantly this means it returns an object which has the shiny __call__() method! This means we can wrap out "foo(10)" inside a lambda, which will return the object which Tk will call, which will in turn call foo(10). Tada, you've got your callback!
* Okay, it's not a sophisticated answer, but it'll do right?
