Why only some Tkinter callback functions need to have an argument but others don't

callback, python, tkinter

Solution

`Scale` doesn't take an event. It takes the current value. Try this:

def cmd(value):
    print int(value)

If you read the Tk tutorial, it explains this:

There is a `"command"` configuration option, which lets you specify a script to call whenever the scale is changed. Tk will automatically append the current value of the scale as a parameter each time it invokes this script (we saw a similar thing with extra parameters being added to scrollbar callbacks and those on the widgets they scroll).

Or, if you read the actual manpage:

Specifies the prefix of a Tcl command to invoke whenever the scale's value is changed via a widget command. The actual command consists of this option followed by a space and a real number indicating the new value of the scale.

In other words, the way to distinguish them is to read the docs. Unfortunately, the Tkinter docs aren't all that complete—they assume you already know how Tcl/Tk works, or how to look it up yourself. That's why the docs start off with a list of links to sources of Tk documentation.

If you prefer to figure it out by trial and error, it's not that hard to see what gets passed:

def cmd(*args):
    print('Scale command says {}'.format(args))

def enable(*args):
    print('Button command says {}'.format(args))

But this won't always tell you everything you need to know; there are other callbacks whose arguments aren't obvious enough to figure out without a lot more work, or which are configurable (e.g., the validate callback).

Problem

I'm using Python 2.7, if that matters. Here is a code I wrote for fun: ``` def p(): root = Tk() def cmd(event): print int(slider.get()) slider = Scale(root, orient = "horizontal", from_ = 0, to = 100, command = cmd, state = "disabled") def enable(): slider.config(state = "active") b = Button(root, text = "Enable slider", command = enable) b.grid() slider.grid(row = 1) root.mainloop() ``` For this code, I'm wondering why the command for Scale requires an event, but that for Button does not. It seems that for some widgets in Tkinter their commands need to have "event" as an argument, and other don't. Why? How to distinguish them? Thanks.

Original source