本文介绍了Python:Tkinter:动态创建标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
限时送ChatGPT账号..我正在尝试动态创建标签,但语法无效.你能帮我看看我缺少什么或任何其他选择
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()
推荐答案
你不应该使用 exec
.如果您想将计算出的名称与循环中的小部件相关联,请使用字典:
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
如果您真的不关心名称是什么,您可以将小部件存储在列表而不是字典中,然后使用整数索引引用它们(例如:labels[0]
、labels[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).
这篇关于Python:Tkinter:动态创建标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论