如何为列表中的每个项目创建tkinter标签?

2024-06-28 20:45:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望tkinter为列表中的每个项目创建一个标签。问题:此列表可能有不同的长度,因为它基于用户输入

我设法为列表中的每个项目创建了一个变量。但是,如果在编写程序时不知道每个变量的名称,如何访问它们(赋值Labelvar_name.grid()

keys = ["foo", "bar"]
count = 0

for key in keys:
    
    labelname = "label_w_" + str(key)
    globals()[labelname] = None

    # I can access the first variable created statically, but what about the others?
    label_w_foo = Label(window, text = key)
    label_w_foo.grid(row = count, column = 1)
    count += 1

window.update()

Tags: the项目key用户列表footkintercount
1条回答
网友
1楼 · 发布于 2024-06-28 20:45:38

这能回答问题吗

from tkinter import *
window =Tk()
keys = ["foo", "bar"]
count = 0
labels=[]
def change_text():
    for j,l in enumerate(labels):
        l.config(text=str(keys[j])+str(j))
for key in keys:
    # I can access the first variable created statically, but what about the others?
    labels.append(Label(window,text=key))
    labels[count].grid(row = count, column = 1)
    count += 1
print(labels)
Button(window,text="Change Text",command=change_text).grid(row=count, column=0)
window.mainloop()

相关问题 更多 >