使用for循环更新Tkinter中的标签

时间:2018-05-15 02:34:56

标签: python tkinter

所以我尝试使用for循环在10 tkinter Label上动态打印列表中的项目。目前我有以下代码:

labe11 = StringVar()
list2_placer = 0
list1_placer = 1
mover = 227
for items in range(10):
    item_values = str(list1[list1_placer] + " " +list2[list2_placer])
    Label(canvas1, width="100", height="2",textvariable=labe11).place(x=200,y=mover)
    labe11.set(item_values)
    list1_placer = list1_placer +1
    list2_placer = list2_placer +1
    mover = mover +50

其中list1list2是包含来自单独函数的字符串或整数的列表,并且包含10个以上的项目,只需要前10个。

目前,这只是在10个单独的标签上打印列表中的最后一项。 提前致谢!

1 个答案:

答案 0 :(得分:1)

为每个StringVar使用不同的Label。目前,您只需将相同的标签传递给所有标签,因此当您更新它们时,它们会一起更新。

这是一个例子。你没有给出一个完全可运行的程序,所以我不得不填补空白。

from tkinter import Tk, Label, StringVar

root = Tk()

list1 = [1,2,3,4,5]
list2 = [6,7,8,9,10]

for v1, v2 in zip(list1, list2):

    item_values = '{} {}'.format(v1, v2)
    sv = StringVar()
    lbl = Label(root, width="100", height="2",textvariable=sv).pack()

    sv.set(item_values)

root.mainloop()
相关问题