2

So I want to use trace() inside a loop. The problem is the function that gets called by the trace passes on variables using the i. It results in only the last string Var in the list being called, instead of all.

What the program is meant to do is create a list of entries and assign a string value to each entry, then whenever you type in the entry .trace() is used to check if entry should be validated. eg [False, 20] False means that it doesnt matter if it's letters or numbers and 20 is the char limit

        self.label_list = [["First Name:","E",[False, 20]], ["Age","E",[False, 20]], ["Do you have a mobile phone?: ","RB", ["Yes", "No"]], ["Mobile Phone:", "HE",[False, 20]]]
        self.string_var_list = []
        self.old_value_list = []
        for i in range(len(self.label_list)):
            self.string_var_list.append(StringVar())
            self.old_value_list.append("")

         self.entry_builder()

    def entry_builder(self):
        self.entry_list = []
        rows = 0
        current = 0
        for i in range(len(self.label_list)):
            if self.label_list[i][1] == "E":
                self.entry_list.append(Entry(self.frame2, width=30, textvariable = self.string_var_list[i]))
                self.entry_list[current].configure(command = self.checkgiver())
                self.entry_list[current].grid(row=len(self.entry_list), column =1, padx=(60,10))
                current += 1

    def checkgiver(self):
        local_list = []
        print("good")
        for i in range(len(self.label_list)):
            if self.label_list[i][1] == "HE" or self.label_list[i][1] == "E":
                    print(self.label_list[i][2][1])
                    self.string_var_list[i].trace('w', lambda *args: self.check_name(self.string_var_list[i], len(self.string_var_list[i].get()),
                                                                                            self.label_list[i][2][0],self.label_list[i][2][1]))

    def check_name(self, b, c, Type, Len):
        if c > Len:
            b.set(b.get()[:Len])

1 Answers1

0

solved it by creating another function and calling it inside the checkgiver and passing i to it

                self.anotherfunc(i)

    def anotherfunc(self,i):
        self.trace_list.append(self.string_var_list[i].trace('w', lambda *args: self.check_name(self.string_var_list[i], len(self.string_var_list[i].get()),
                                                                                            self.label_list[i][2][0],self.label_list[i][2][1])))