0

So, i am writing a program which change color of label when mouse is hovering over it. There are n Labels i tried to bind them with and yeah it works fine for one label object. But whenever i bind it with multiple Labels objects it only change color of the Last Label object. here is my code

    def list_all(self):
          all_l = []
          contents = self.com.get_all()
        self.flbox.delete("all") #Clearing the canvas 
        j = 0
        for i in contents:
            if i == "d":
                for d in contents[i]:
                    line = Label(self.flbox)
                    line.config(text=d,
                            font="Arial 12",
                            compound=LEFT,
                            image=self.fol_img,
                            bg="white",
                            anchor="nw",
                            width=self.cright.winfo_width()
                            )
                    line.bind("<Motion>", lambda event: self.m(event, line))
                    line.bind("<Leave>", lambda event: self.n(event, line))
                    self.flbox.create_window(0, j+24, window=line, anchor="nw", width=self.cright.winfo_width())
                all_l.append(line)
                j += 24
preet
  • 13
  • 4

1 Answers1

0

You should create a local variable as a copy. Otherwise, the line variable is over written with every iteration

line.bind("<Motion>", lambda event, line=line: self.m(event, line))
line.bind("<Leave>", lambda event, line=line: self.n(event, line))
                    

lambda won't copy the value from line to self.m(event, line). It will use line as reference, which is changed with every iteration. That is why we need to create a local variable