Callback functions arguments
Peter Otten
__peter__ at web.de
Mon Oct 27 04:52:33 EDT 2014
ast wrote:
> Hi
>
> In this web site at example n°5
> http://fsincere.free.fr/isn/python/cours_python_tkinter.php
>
> A program is using the "Scale" widget from tkinter module.
> Here is a piece of code:
>
> Valeur = StringVar()
>
> echelle = Scale(Mafenetre, from_=-100, to=100, resolution=10, \
> orient=HORIZONTAL, length=300, width=20, label="Offset", \
> tickinterval=20, variable=Valeur, command=maj)
>
> The "maj" callback function is:
>
> def maj(nouvelleValeur):
> print(nouvelleValeur)
>
> When the user move the scale with the mouse, the new position
> is supposed to be printed on the python shell.
>
> The "maj" function has an argument "nouvelleValeur" but no
> argument is passed through the Scale widget.
>
> So how the hell Python knows that it has to pass parameter
> "Valeur" to the "maj" function ?
Python doesn't "know" it has to pass an argument, it just does it. Change
the callback to
def maj():
print("no args")
and you'll get an error. If I were to guess
> echelle = Scale(Mafenetre, from_=-100, to=100, resolution=10, \
> orient=HORIZONTAL, length=300, width=20, label="Offset", \
> tickinterval=20, variable=Valeur, command=maj)
you probably are misled by the 'command=maj' part in the above line. This
means that the function is passed and is different from command=maj() where
the *result* of the function is passed.
Here's a self-contained example that may clear things up for you:
>>> def call_them(one, two):
... one(1)
... two(2, 3)
...
>>> def square(a):
... print(a, "*", a, "=", a*a)
...
>>> def product(a, b):
... print(a, "*", b, "=", a*b)
...
>>> call_them(square, product)
1 * 1 = 1
2 * 3 = 6
>>> call_them(product, product)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in call_them
TypeError: product() missing 1 required positional argument: 'b'
call_them() expects that one() takes 1 argument and two() takes 2 arguments.
If the user passes a function that expects a different number of arguments a
TypeError is raised.
More information about the Python-list
mailing list