Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Background:

A GUI table having a "skip combobox" widget allowing user to skip current line from executing. Amount of lines in this GUI varies. This "skip" is created using a for loop.

When selecting "on" or "off" a bind process executes a method called self.but_callback which doing the rest of code.

goal:

Pass i value to self.but_callback, along with event needed to bind.

Code below, shows a try to pass i value directly into self.but_callback(event,i) BUT instead of assigning the right i value it passes the last value of for loop for every skip_button created.

Question: How to pass correct i value while in a loop, when 2 parameters are need to pass using lambda function.

Did not find any answer combining both issues.

   for i in range(len(data_from_file)):

        #Skip button
        self.var.append(tk.StringVar())
        self.var[7].set('On')
        skip_button = ttk.Combobox(inner_frame, width=5, textvariable=self.var[7], values=['On','Off'],state='readonly', justify=tk.CENTER)
        skip_button.bind('<<ComboboxSelected>>',lambda event: self.but_callback(event,i))
        skip_button.grid(row=i+1, column=7, padx=8)


   def but_callback(self,event,x):
        print(x)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
318 views
Welcome To Ask or Share your Answers For Others

1 Answer

It is very common problem with lambda in loop.

It doesn't copy value from i when you create lambda function but it keeps reference to i. So all functions have reference to the same variable (the same place in memory) and they get value from i when they are exceuted.

You have to assign i to argument in lambda (for example x=i) and use this argument x in your function. This way it will copy current value from i and use in lambda function

lambda event, x=i : self.but_callback(event, x)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...