Skip to content Skip to sidebar Skip to footer

Python: Tkinter :dynamically Create Label

I am trying to create Label Dynamically , I am getting invalid Syntax. Can you please help me what i am missing or any alternative crsr = cnxn.execute(query) row_num=

Solution 1:

You should not be using exec. If you want to associate a computed name with a widget in a loop, use a dictionary:

labels = {}
varnum = 0
for row in crsr.fetchall():
    name=f"label#{varnum}"
    labels[name] = tk.Label(frame, text=str(row[0]))
    labels[name].grid(row=row_num, column=column_num
    varnum += 1
    row_num+=1
    column_num+=1

If you don't really care what the name is, you can store the widgets in a list rather than a dictionary, and then reference them using an integer index (eg: labels[0], labels[1], etc).

Solution 2:

Use exec() instead eval()

eval will evaluate a expression, not run it like you want. Think of eval like the argument of a if statement.

Post a Comment for "Python: Tkinter :dynamically Create Label"