Python – returning from a Tkinter callback

The notion of “returning” values from callbacks doesn’t make sense in the context of an event driven program. Callbacks are called as the result of an event, so there’s nowhere to return a value to.

As a general rule of thumb, your callbacks should always call a function, rather than using functools.partial or lambda. Those two are fine when needed, but if you’re using an object-oriented style of coding they are often unnecessary, and lead to code that is more difficult to maintain than it needs to be.

For example:

def compute():
    value = var.get()
    result = square(value)
    list_of_results.append(result)

button = Tk.Button(root, text="click", command = compute)
...

This becomes much easier, and you can avoid global variables, if you create your application as a class:

class App(...):
    ...
    def compute():
        ...
        result = self.square(self.var.get())
        self.results.append(result)

Leave a Comment