Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

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=2
        column_num=0
        Variable_Number=1
        for row in crsr.fetchall():

            test='Column_Label'+str(Variable_Number)+' = tk.Label(frame,text="'+row[0]+'")'



#proper Indentation availabe in code        test1='Column_Label'+str(Variable_Number)+'.grid(row='+str(row_num)+',column='+str(column_num)+')'
            eval(test+';'+test1)
    #        eval(test1)
            row_num+=1
            column_num+=1
        root.update_idletasks()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...