2017-07-24 62 views
0

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

x=1 
for item in finalList: 

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

    x += 1 

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

+2

你的问题是“是否可能”,答案是,很可能是“是”。 – GrumpyCrouton

回答

3

你不需要名字来做这样的事情。您可以将您的小部件放入列表中,然后访问使用索引的小部件。

#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) 
1

可以做你正在尝试做的事情。

我还没遇到需要这样做的情况。

下面是使用exec执行每个循环的命令的示例。

欲了解更多的exec语句可以芦苇一些文档here

注意:避免这种方法,并使用列表/字典方法,而不是。这个例子只是提供关于在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() 
+0

当你在这里时,你也可以用exec创建条目。 :) – Lafexlos

+0

是的。我只想解决OP正在使用的插入功能。 –

相关问题