0

I'm creating 8 labels in for loop with their text and stuff, and I'd aso like to create event for each of them (inside loop), so that when user hovers over every label, it get's shown different text.

I'll just paste the relevant parts:

for index, label in enumerate(labels):
    lab = Tk.Label(self.root, text=label)
    lab_info = PARAMS[label]
    lab.grid(row=index)
    lab.bind('<Enter>', lambda event: self.on_enter(event, lab_info))
    lab.bind('<Leave>', self.on_leave)
    entry = Tk.Entry(self.root)
    entry.grid(row=index, column=1)
    self.entries_dict[label] = entry

def on_enter(self, event, lab_info):
    self.enter = Tk.Label(self.root, text=lab_info, bg='#ffffb3')
    self.enter.grid(row=0, rowspan=3, column=1)

def on_leave(self, event):
    self.enter.destroy()

What works: labels get created, they are layed out as I specified, they have the correct text, etc.

What doesn't work: if I hover over any of them, only the text of the last label created get's printed out. I'm sure I'm missing something, but I've been staring at this for far too long, and it's just become tiresome

EDIT: This is all part of a class, that's why all the self.*

Luka
  • 143
  • 3
  • 12
  • This might provide an explanation, http://stackoverflow.com/a/938493/5781248 . You could try replacing your lambda with `functools.partial(self.on_enter, lab_info)` – J.J. Hakala Jun 19 '16 at 10:42
  • 2
    Change your callback to `lambda event, li= lab_info: self.on_enter(event, li))`. That will set the default value of `li` to the value that `lab_info` has when the lambda is created. Your current lambda uses the value that `lab_info` has when the lambda is called, which will be the value assigned to it on the last iteration of your for loop. – PM 2Ring Jun 19 '16 at 10:48
  • Thank you @PM 2Ring, that worked! It also makes total sense. – Luka Jun 19 '16 at 10:54

0 Answers0