Tkinter Click 事件突出显示单击的标签?
Tkinter Click Event Highlights the Label Clicked?
我正在尝试在 tkinter 中编写一个程序,其中有 table 个标签,当您单击标签时,该行会突出显示。
我的代码目前看起来像这样定义点击事件和标签(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)
但是,当我单击标签时,它会告诉我 "Label has no attribute '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 是所有帧(或行)的字典。还有多田!突出显示 table!
的单击行
像这样修改您的 callback()
函数:
def callback(event):
event.widget.config(bg='blue')
希望这对您有所帮助。 :)
我正在尝试在 tkinter 中编写一个程序,其中有 table 个标签,当您单击标签时,该行会突出显示。
我的代码目前看起来像这样定义点击事件和标签(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)
但是,当我单击标签时,它会告诉我 "Label has no attribute '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 是所有帧(或行)的字典。还有多田!突出显示 table!
的单击行像这样修改您的 callback()
函数:
def callback(event):
event.widget.config(bg='blue')
希望这对您有所帮助。 :)