0

I have a dictionnary full of StringVar that I want to link with a dictionnary full of functions. Problem: I can't automatise the .trace() method in a for loop (and I don't understand why because it works like a charm in the second example).

THIS WORKS:

var_dict["name"].trace("w", lambda name, index, mode, x="name": func_dict["name"](x))
var_dict["surname"].trace("w", lambda name, index, mode, x="surname": func_dict["surname"](x))
var_dict["age"].trace("w", lambda name, index, mode, x="age": func_dict["age"](x))

THIS DOESN'T WORK (all widgets are bind to the last function):

for key in ["name","surname","age"]:
    var_dict[key].trace("w", lambda name, index, mode, x=key: func_dict[key](x))

HERE IS THE CODE OF THE GOOD EXAMPLE:

import tkinter as tk

app = tk.Tk()

key_list = ["name","surname","age"]

entry_dict = {}
var_dict = {}
func_dict = {}

def foo(key):
    print(key)
func_dict["name"] = foo
func_dict["surname"] = foo

def foo(key):
    print("I have others things to do")
func_dict["age"] = foo

for key in key_list:
    var_dict[key] = tk.StringVar()
    entry_dict[key] = tk.Entry(app,textvariable=var_dict[key])
    entry_dict[key].pack()
var_dict["name"].trace("w", lambda name, index, mode, x="name": func_dict["name"](x))
var_dict["surname"].trace("w", lambda name, index, mode, x="surname": func_dict["surname"](x))
var_dict["age"].trace("w", lambda name, index, mode, x="age": func_dict["age"](x))

app.mainloop()

HERE IS THE CODE OF THE BAD EXAMPLE:

import tkinter as tk

app = tk.Tk()

key_list = ["name","surname","age"]

entry_dict = {}
var_dict = {}
func_dict = {}

def foo(key):
    print(key)
func_dict["name"] = foo
func_dict["surname"] = foo

def foo(key):
    print("I have others things to do")
func_dict["age"] = foo

for key in key_list:
    var_dict[key] = tk.StringVar()
    entry_dict[key] = tk.Entry(app,textvariable=var_dict[key])
    entry_dict[key].pack()
    var_dict[key].trace("w", lambda name, index, mode, x=key: func_dict[key](x))

app.mainloop()

I don't understand why it doesn't work... (like really no idea...) because it should work exactly the same way !!! :/

  • This is the usual issue of using lambdas in for loops, you need to replace `key` by `x` to get the right function: `lambda name, index, mode, x=key: func_dict[x](x)` – j_4321 Aug 03 '20 at 12:43
  • Thanks a lot ! quick and perfect ! (I'm not still sure why it works like that but it works !) –  Aug 03 '20 at 12:45
  • Look at the question https://stackoverflow.com/questions/7546285/creating-lambda-inside-a-loop, the answer is here. That's why your question was closed as duplicate. – j_4321 Aug 03 '20 at 12:47
  • I just saw the other post but I didn't get it in the first place (we don't know what we don't know). At the end, this is the good solution but you understand it after having the solution, I prefer your answer, I know from where it comes now). –  Aug 03 '20 at 12:52

0 Answers0