Updating Labels in Tkinter with for loop

老子叫甜甜 提交于 2021-01-29 09:29:41

问题


So I'm trying to print items in a list dynamically on 10 tkinter Labels using a for loop. Currently I have the following code:

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

Where list1 and list2 are lists containing strings or integers from a separate function and have more than 10 items and only the first 10 are wanted.

Currently this just prints the last item in the list on 10 separate labels. Thanks in advance!


回答1:


Just use a distinct StringVar for each Label. Currently, you just pass the same one to all the labels, so when you update it they all update together.

Here's an example. You didn't give a fully runnable program, so I had to fill in the gaps.

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


来源:https://stackoverflow.com/questions/50341529/updating-labels-in-tkinter-with-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!