Tkinter无法正确更新标签

时间:2018-12-17 20:38:59

标签: python python-3.x for-loop tkinter label

这是代码:

for row in results:
    ColumnCounter += 1
    id_list.append(row['ID'])
    #print(id_list)  # DEBUG
    tk.Label(DisplayWindow, text=str(RowCounter - 1), fg="black", font="none 8 bold").grid(row=RowCounter, column=ColumnCounter, sticky=W)
    ColumnCounter += 1
    firstname_list.append(row['FIRST_NAME'])
    #print(firstname_list)  # DEBUG
    tk.Label(DisplayWindow, text=firstname_list[ListCounter], fg="black", font="none 8 bold").grid(row=RowCounter, column=ColumnCounter, sticky=W)
    ColumnCounter += 1
    surname_list.append(row['SURNAME'])
    #print(surname_list)  # DEBUG
    tk.Label(DisplayWindow, text=surname_list[ListCounter], fg="black", font="none 8 bold").grid(row=RowCounter, column=ColumnCounter, sticky=W)
    ColumnCounter += 1
    username_list.append(row['USERNAME'])
    #print(username_list)  # DEBUG
    tk.Label(DisplayWindow, text=username_list[ListCounter], fg="black", font="none 8 bold").grid(row=RowCounter, column=ColumnCounter, sticky=W)
    ColumnCounter += 1
    email_list.append(row['EMAIL'])
    #print(email_list)  # DEBUG
    tk.Label(DisplayWindow, text=email_list[ListCounter], fg="black", font="none 8 bold").grid(row=RowCounter, column=ColumnCounter, sticky=W)
    tk.Button(DisplayWindow, text="Select Row", command=lambda CurrentValue=row: [SelectRow(CurrentValue['ID'], CurrentValue['FIRST_NAME'], CurrentValue['SURNAME'], CurrentValue['USERNAME'], CurrentValue['EMAIL']), DisplayWindow.destroy()]).grid(row=RowCounter, column=ColumnCounter + 1, sticky=E)

    RowCounter += 1
    ColumnCounter = -1
    ListCounter += 1

每次重新运行此for循环时,标签均无法正确更新其文本。它显示旧文本的一半内容和新文本的一半内容。我尝试在所有标签中用textvariable=SomeStringVariable_NameStringVar)替换文本,但同样,同样的问题。我该如何解决?

(变量结果是一个字典。更准确地说,它是从MySQL数据库获取的内容。)

1 个答案:

答案 0 :(得分:0)

可以通过为label分配背景色,并将"sticky=W"选项设置为"sticky=W+E"来解决重叠问题。

这样,新背景将(覆盖并覆盖)完全覆盖旧文本。

(我认为)这是您可能追求的一种可能的解决方案。以下是有关标签管理的一些建议,以获得对标签的更多控制。

如果标签本身中的信息未更新:

将每个标签分配给一个变量。然后,每次运行循环时,请使用widget.configure(option=value)

更新信息
label_id_list.configure(text=str(RowCounter - 1))
label_firstname_list.configure(text=firstname_list[ListCounter])
label_surname_list.configure(text=surname_list[ListCounter])
label_username_list.configure(text=username_list[ListCounter])
label_email_list.configure(text=email_list[ListCounter])
button_email_list.configure(command=lambda CurrentValue=row: [SelectRow(CurrentValue['ID'], CurrentValue['FIRST_NAME'], CurrentValue['SURNAME'], CurrentValue['USERNAME'], CurrentValue['EMAIL']))

标签信息将更新;无需致电widget.grid()