在 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 声明的更多信息,您可以阅读一些文档 here

注意:避免使用此方法并改用 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()