使用 for 循环更新 Tkinter 中的标签 [英] Updating Labels in Tkinter with for loop

查看:32
本文介绍了使用 for 循环更新 Tkinter 中的标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

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

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

推荐答案

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

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

这篇关于使用 for 循环更新 Tkinter 中的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆