Tkinter – how to dynamically create labels named by items in list?

Question:

Last time I programmed something when Basic was new to the world. Now I’ve dived into python and can’t figure out where I’m doing what wrong. The application I am creating loads a large amount of data, processes it and then displays the results. The question is how to ensure that there is exactly one value from the list in each label. the program set in this way will deliver the result shown in the image.

import customtkinter

list_names = ("George","Johny","Mike","Anna")

window = customtkinter.CTk()
frame = customtkinter.CTkFrame(window)
my_data = customtkinter.StringVar()

frame.grid(row=0, column=0)

for i in range(len(list_names)):
    name = list_names[i]
    my_data.set(name)
    customtkinter.CTkLabel(frame, text=f'{1+i}.Name ').grid(row=i, column=0)
    customtkinter.CTkLabel(frame, textvariable=my_data).grid(row=i, column=1)

# for label in frame.winfo_children(): # this will destroy labels
    # label.destroy()

window.mainloop()

result

Asked By: smokeflypaper

||

Answers:

Just move the my_data variable inside of the loop and bob’s your uncle.

import customtkinter

list_names = ("George","Johny","Mike","Anna")

window = customtkinter.CTk()
frame = customtkinter.CTkFrame(window)
frame.grid(row=0, column=0)

for i in range(len(list_names)):
    name = list_names[i]
    my_data = customtkinter.StringVar()
    my_data.set(name)
    customtkinter.CTkLabel(frame, text=f'{1+i}.Name ').grid(row=i, column=0)
    customtkinter.CTkLabel(frame, textvariable=my_data).grid(row=i, column=1)

window.mainloop()
Answered By: Alexander

thnx folks it works great now 😉

Answered By: smokeflypaper
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.