Tkinter Click事件突出显示了单击的标签?

问题描述 投票:0回答:1

我正在尝试在tkinter中编写一个程序,该程序中有一个标签表,当您单击标签时,该行将突出显示。

我的代码当前看起来像这样,用于定义click事件和标签(dbf是它们所容纳的框架):

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)

但是,当我单击标签时,它告诉我“标签没有属性'bg'”。为什么bg在这里不起作用,但是在定义标签时起作用?

有什么方法可以执行我要执行的操作并使行被单击以突出显示?

((我现在知道,如果可行,它将仅突出显示当前标签。我想出了如何在突出显示该行之后将其突出显示,但在这里被卡住了。)

任何帮助将不胜感激!谢谢!

编辑:更正了代码中的.bind行(感谢acw)

Edit2:弄清楚如何使整行改变颜色。将每一行放在一个框架中,然后称为框架以及框架的所有子项。这样回调事件看起来像这样:

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')

其中row_dict是所有帧(或行)的字典。和田田!突出显示表中单击的行!

python tkinter mouseclick-event
1个回答
1
投票

像这样修改callback()函数:

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

希望这会有所帮助。 :)

© www.soinside.com 2019 - 2024. All rights reserved.