Why only some Tkinter callback functions should have an argument, but others not

I am using Python 2.7 if that matters.

Here is the 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 wonder why an event is required for the Scale command, but for Button it is not. It seems that for some widgets in Tkinter, their commands should have an β€œevent” as an argument, while others should not. What for? How to distinguish them?

Thanks.

+4
source share
2 answers

Scale does not accept the event. It takes the current value. Try the following:

 def cmd(value): print int(value) 

If you read the Tk tutorial , he explains this:

There is a "command" configuration option that allows you to specify a script to invoke whenever the scale changes. Tk automatically adds the current scale value as a parameter each time this script is called (we saw a similar thing with the addition of additional parameters to scroll callbacks and scroll scrolls).

Or, if you read the actual manpage :

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

In other words, the way to distinguish them is to read documents. Unfortunately, Tkinter docs are not all that much - they assume that you already know how Tcl / Tk works, or how to search for it yourself. This is why documents begin with a list of links to Tk documentation sources.

If you prefer to find out by trial and error, it’s not so difficult to understand what happened:

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

But this will not always tell you everything you need to know; there are other callbacks whose arguments are not obvious enough to be found without a lot of work or that can be configured (for example, check the callback).

+4
source

When you configure the binding (using the bind command), the callback always receives the event object.

When you work with the command attribute of a widget, different widgets send different data to the command. In this case, they never send an event, but will send other data types. This is simply because different teams do different things.

The timeline widget is no different - you say that the callback accepts the event, but this is a lie. It skips the current value of the scale widget, not the event object.

+2
source

All Articles