callisto
callisto

Reputation: 55

Callback parameters using lambda

I started Python(2.7.3) two days ago and I need to use parameters in my GUI callbacks functions. I've been looking for any information here and on effbot, but I cant find out what is wrong in my case.

from Tkinter import *
fenetre = Tk()
var_texte = StringVar()
ligne_texte = Entry(fenetre, textvariable=var_texte ,width=30)

def callback(s):
    print("we got there with :"+s)

trace_name = var_texte.trace_variable("w",lambda: callback(ligne_texte.get()))
ligne_texte.pack()
fenetre.mainloop()

I tried to use lambda to get my param passed but i get this error when I type text into the Entry:

Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__
return self.func(*args)
TypeError: <lambda>() takes no arguments (3 given)

I found a post here which proposed to replace lambda: with lambda x:, but I get another error with TypeError: <lambda>() takes exactly 1 argument (3 given)

Any explanation or source or information would be very appreciated :)

Upvotes: 0

Views: 2682

Answers (2)

hivert
hivert

Reputation: 10667

As the error message says, StringVar.trace_variable is called with three argument by the framework. So your lambda function should accept those three argument:

lambda name, idx, mode: ...

From http://staff.washington.edu/rowen/ROTKFolklore.html here is the description of the arguments:

  • The name of the Tk variable. This is not the Tk variable object itself, but you can use the name to get or set the value via root.globalgetvar(name) and root.globalsetvar(name). Unfortunately, I have not found any way to obtain the actual Tk variable object from its name; root.nametowidget(varName) does not seem to work for Tk variables.
  • The variable index, if the Tk variable is an array, else an empty string. I have no idea how to create a Tk variable array in Tkinter (but it is easy in Tk). If you figure it out, you can then determine if the index is a string representation of an integer, or an integer (my guess is it's a string).
  • The access mode, one of "w", "r" or "u".

Upvotes: 3

Joel Cornett
Joel Cornett

Reputation: 24788

If you are not interested in the parameters being passed to the callback, you can use:

lambda *args: callback(ligne_texte.get())

The documentation for the so-called "splat" operator (*) can be found here.

Upvotes: 1

Related Questions