Alex Horn
Alex Horn

Reputation: 97

Tkinter Click Event Highlights the Label Clicked?

I'm trying to write a program in tkinter where there is a table of labels and when you click on a label, that row is highlighted.

My code currently looks like this for defining the click event and labels (dbf is the frame they're held in):

def callback(event):
    event.widget.bg('blue')

for i in range(0,len(table_values)):
    num_lab1 = tk.Label(dbf, text=table_values[i][0], width=10, justify='left', bg='white')
    num_lab1.bind("<Button-1>", callback)
    num_lab1.grid(row=i+1, column=0)

    name_lab1 = tk.Label(dbf, text=table_values[i][1], width=20, justify='left', bg='white')
    name_lab1.bind("<Button-1>", callback)
    name_lab1.grid(row=i+1, column=1)

    comm_lab1 = tk.Label(dbf, text=table_values[i][2], width=50, justify='left', bg='white', wraplength=250)
    comm_lab1.bind("<Button-1>", callback)
    comm_lab1.grid(row=i+1, column=2)

However when I click a label, it tells me "Label has no attribute 'bg'". Why does bg not work here but does work in defining the label?

Is there any way to do what I'm after and get the row clicked to be highlighted?

(I know that right now, if it worked it would only highlight the current label. I was going to figure out how to highlight the row after I figured this, but got stumped here.)

Any help would be greatly appreciated! Thanks!

Edit: Corrected .bind lines in code (thanks to acw)

Edit2: Figured out how to get the whole row to change colour. Placed each row in a frame, then called the frame and all the frame's children. Such that the callback event looked like this:

def callback(event):
    # Makes all rows white
    for j in row_dict:
        for k in row_dict[j].winfo_children():
            k.configure(bg='white')
    # Makes clicked row highlighted
    for l in event.widget.master.winfo_children():
        l.configure(bg='#a1c1ff')

Where row_dict is a dictionary of all the frames (or rows). And Tada! Highlighting the clicked row of a table!

Upvotes: 0

Views: 1891

Answers (1)

Devansh Soni
Devansh Soni

Reputation: 771

Modify your callback() function like this:

def callback(event):
    event.widget.config(bg='blue')

Hope this helps. :)

Upvotes: 1

Related Questions