Python:Tkinter:动态创建标签

编程入门 行业动态 更新时间:2024-10-28 19:32:06
本文介绍了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:关键词]

本文发布于:2023-04-30 05:32:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1390259.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:标签   动态   Python   Tkinter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!