Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...