user5849928
user5849928

Reputation:

How can I add binds to a dynamic list of widgets in Tkinter (Python)

I'm trying to create labels from a list, bind the '<Enter>' and '<Leave>' events to make the background colors change when the label is hovered over (blue by default, red when hovered over), then pack the labels.

Currently, I'm adding each label to a dictionary, and referencing that, but when the cursor enters any label, the last (and only the last) label's background color changes.

from tkinter import *


random_list = ['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQR']


class x:
    def __init__(self, master):
        y = {}
        for i in random_list:
            y[i] = Label(master, text=i, bg='#00f')
            y[i].pack()
            y[i].bind('<Enter>', lambda event: y[i].configure(background='#f00'))
            y[i].bind('<Leave>', lambda event: y[i].configure(background='#00f'))


root = Tk()
app = x(root)
root.mainloop()

Upvotes: 0

Views: 303

Answers (1)

SneakyTurtle
SneakyTurtle

Reputation: 1857

Your lambda expression is capturing the i, as it were, and causing this issue.

You should be able to fix this by specifying i = i within the lambda definition.

i.e., your lines with lambda statements should look like this:

y[i].bind('<Enter>', lambda event, i=i: y[i].configure(background='#f00'))
y[i].bind('<Leave>', lambda event, i=i: y[i].configure(background='#00f'))

Upvotes: 3

Related Questions