繁体   English   中英

在tkinter中的文本小部件的实例名称中使用变量

[英]Using variable in instance name of text widget in tkinter

我试图在文本框实例名称中使用变量,以便在for循环中对它们进行随机排序。 例如,我要尝试从列表中填充14个文本小部件(infoBox1至InfoBox14)。 所以我要做的是以下几点:

x=1
for item in finalList:

     self.infoBox(x).insert(END, item)

     x += 1

然后随x的增加填充框。 有人可以帮忙吗?

您不需要名称就可以执行此操作。 您可以将小部件放在列表中,然后使用索引访问它们。

#you can create like this. Used -1 as index to access last added text widget
text_list = []
for idx in range(14):
    text_list.append(tkinter.Text(...))
    text_list[-1].grid(...)

#then you can easily select whichever you want just like accessing any item from a list

text_list[x].insert(...)
#or directly
for idx, item in enumerate(finalList):
    text_list[idx].insert("end", item)

可以做您想做的事。

我没有遇到过需要以这种方式进行处理的情况。

这是一个使用exec在每个循环中执行命令的示例。

有关exec语句的更多信息,您可以在此处查看一些文档

注意:避免使用此方法,而使用list / dict方法。 这个例子只是为了提供有关如何在python中实现知识的知识。

from tkinter import *

class tester(Frame):
    def __init__(self, parent, *args, **kwargs):
        Frame.__init__(self, parent, *args, **kwargs)       

        self.parent = parent
        self.ent0 = Entry(self.parent)
        self.ent1 = Entry(self.parent)
        self.ent2 = Entry(self.parent)
        self.ent0.pack()
        self.ent1.pack()
        self.ent2.pack()

        self.btn1 = Button(self.parent, text="Put numbers in each entry with a loop", command = self.number_loop)
        self.btn1.pack()

    def number_loop(self):
        for i in range(3):
            exec ("self.ent{}.insert(0,{})".format(i, i))


if __name__ == "__main__":
    root = Tk()
    app = tester(root)
    root.mainloop()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM